In this post, we are going to code a simple HTTP server implemented in Golang. That server will be a simple implementation able to receive and process GET and POST operations. The project layout used in this example was based on the https://github.com/golang-standards/project-layout.
I am going to use only standard Golang packages, so the main function uses only the HTTP package. For this example, we will implement the GET and POST operation for a Customer. This is the Customer structure.
json:"id" and json:"name" indicates what is the node name for the json parsingIn our main function, we define the handler to intercept the request to our Customer endpoint.
The http.ListenAndServe(":8080", nil) defines that the server will be listening in port 8080 and will be using the default implementation DefaultServeMux as a handler.Next step, we need to implement the customerHandler
Based on the http.Request.Method we decide to process a GET or a POST operation. Let's review the model implementation to process a Customer. The GetCustomer method returns a Customer array JSON object.The PostCustomer method receives a byte array that represents a Customer JSON object.
We could run this implementation running the Go implementation.
Then we could sent a GET request
The server response shows an array with all the customer selected.
For more details, feel free to clone the code repository in Github and run the http server locally, https://github.com/mccantuta/simple-http-server-go.