Build a JSON over HTTP Server

Distributed Services with Go — by Travis Jeffery (12 / 84)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Build a Commit Log Prototype | TOC | Run Your Server 👉

Now we’ll write our JSON/HTTP web server. A Go web server comprises one function — a net/http HandlerFunc(ResponseWriter, *Request) — for each of your API’s endpoints. Our API has two endpoints: Produce for writing to the log and Consume for reading from the log. When building a JSON/HTTP Go server, each handler consists of three steps:

  1. Unmarshal the request’s JSON body into a struct.
  2. Run that endpoint’s logic with the request to obtain a result.
  3. Marshal and write that result to the response.

If your handlers become much more complicated than this, then you should move the code out, move request and response handling into HTTP middleware, and move business logic further down the stack.

Let’s start by adding a function for users to create our HTTP server. Inside your server directory, create a file called http.go that contains the following code:

LetsGo/internal/server/http.go

​ ​package​ server

​ ​import​ (
​ ​"encoding/json"​
​ ​"net/http"​

​ ​"github.com/gorilla/mux"​
​ )

​ ​func​ NewHTTPServer(addr ​string​) *http.Server {
​ httpsrv := newHTTPServer()
​ r := mux.NewRouter()
​ r.HandleFunc(​"/"​, httpsrv.handleProduce).Methods(​"POST"​)
​…

--

--