In this section, we will use the design patterns already described to build a REST API in Golang. It's relatively straightforward to set up a web server using the Golang net/http package in the standard library. A hello world program is described as follows:
package main
import ( "fmt" "log" "net/http" ) func main() { // setup router http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { log.Println("path", r.URL.Path) fmt.Fprintf(w, "pong! on %sn", r.URL.Path) }) // listen and serve err:= http.ListenAndServe(":9090", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
It sets up a handler at a specific URL path, which takes in the request pointer and a response writer.
The ListenAndServe() method does the following:
- Instantiates an Http server
- Calls net.Listen("tcp", addr) to listen on TCP for the defined port (here 9090)
- Starts a loop and accept requests in the loop body
- Starts a Goroutine for every request
- Reads the request data
- Searches for the handler for that URL, and executes the code there
The crux of any Go web application is the ability to serve each request as a separate Goroutine, as shown in the following diagram:
This ability increases the scalability and resource-efficiency of the server immensely.