(Notes from Microservices With Go by Nic Richardson)
Building a web server in Go is pretty straightforward, using the HTTP package. We’ll be using net/http package.
Example: basic_server.go
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
port := 8080
http.HandleFunc("/helloworld", helloWorldHandler)
log.Printf("Server starting on port %v\n", 8080)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", port), nil))
}
func helloWorldHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello World\n")
}
HandleFunc() on the http package creates a handler, mapping the path in the first parameter to the function in the second parameter.
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)
ListenAndServe() starts an HTTP server with a given address and handler. Here, we are binding it to port 8080. The handler is usually nil, which means to use DefaultServeMux. Handle and HandleFunc add handlers to DefaultServeMux.
If the ListenAndServe function fails to start a server it will return an error, the most common reason for this is that you may be trying to bind to a port that is already in use on the server. In our example, we are passing the output of ListenAndServe straight to log.Fatal(error), which is a convenience function equivalent to calling fmt.Print(a ...interface{}) followed by a call to os.Exit(1). Since ListenAndServe blocks if the server starts correctly we will never exit on a successful start.
$ go run ./basic_server.go
You should now see the application output:
Server starting on port 8080
If you see something like the following, it means you are already running an application on port 8080
listen tcp :8080: bind: address already in use exit status 1
You can check the list of running programs using this command
$ ps -aux | grep 'go run'
If there is another program running, you can kill it. If that is not possible, choose a different port for your program.
Once the server is up and running, type in the URI http://127.0.0.1:8080/helloworld or http://localhost:8080/helloworld and if things are working correctly you should see the following response from the server:
Hello World
If you see the above response, that means you have your a basic http server in Go up and running.