Run Your Server

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Build a JSON over HTTP Server | TOC | Test Your API 👉

The last code you need to write is a main package with a main function to start your server. In the root directory of your project, create a cmd/server directory tree, and in the server directory create a file named main.go with this code:

LetsGo/cmd/server/main.go

​ ​package​ main

​ ​import​ (
​ ​"log"​

​ ​"github.com/travisjeffery/proglog/internal/server"​
​ )

​ ​func​ main() {
​ srv := server.NewHTTPServer(​":8080"​)
​ log.Fatal(srv.ListenAndServe())
​ }

Our main function just needs to create and start the server, passing in the address to listen on (localhost:8080) and telling the server to listen for and handle requests by calling ListenAndServe. Wrapping our server with the *net/http.Server in NewHTTPServer saved us from writing a bunch of code here — and anywhere else we’d create an HTTP server.

It’s time to test our slick new service.

👈 Build a JSON over HTTP Server | TOC | Test Your API 👉

Distributed Services with Go by Travis Jeffery can be purchased in other book formats directly from the Pragmatic Programmers. If you notice a code error or formatting mistake, please let us know here so that we can fix it.

--

--