Serving our API with one function
A web service is nothing more than a simple Go program that binds to a specific HTTP address and port and serves requests, so we get to use all our command-line tool writing knowledge and techniques.
Tip
We also want to ensure that our main
function is as simple and modest as possible, which is always a goal of coding, especially in Go.
Before writing our main
function, let's look at a few design goals of our API program:
We should be able to specify the HTTP address and port to which our API listens and the address of the MongoDB instances without having to recompile the program (through command-line flags)
We want the program to gracefully shut down when we terminate it, allowing the in-flight requests (requests that are still being processed when the termination signal is sent to our program) to complete
We want the program to log out status updates and report errors properly
Atop the main.go
file, replace the main
function placeholder with the following code...