create a http server on a specific port and host in go

To create an HTTP server on a specific port and host in Go, you can use the ListenAndServe() function from the net/http package.

Here's an example code snippet that creates a HTTP server listening on port 8080, and the host being any IP address that the machine running the Go program has:

main.go
package main

import (
    "fmt"
    "net/http"
)

func main() {
    port := "8080"
    host := ""

    fmt.Printf("Server started on %s:%s\n", host, port)

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, World!")
    })

    err := http.ListenAndServe(host+":"+port, nil)

    if err != nil {
        fmt.Println(err)
    }
}
382 chars
24 lines

In the code snippet above:

  • We import the net/http and fmt packages.
  • We define a variable port with the value "8080" and a variable host with the value "".
  • We use fmt.Printf() to print the message "Server started on %s:%s\n", where %s is replaced with host and port.
  • We define a handler function for the root route ("/") that writes "Hello, World!" to the response writer.
  • We use the http.ListenAndServe() function to create the server listening on host+":"+port. If there is any error, it will be printed to the console.

related categories

gistlibby LogSnag