Creating an HTTP Server Using Gin
Learn to create an HTTP server in Go using the Gin web framework.
We'll cover the following...
What is an HTTP server?
HTTP is the protocol that's used to serve most of the content on the web. There are a few components involved in this process:
Client: This is the software that's used to access services made available by the server, such as the web browser.
Server: This is a piece of software that can process HTTP requests and return a response.
Endpoint or API Endpoint: This is the path exposed by the server to perform a specific operation on the resource being served.
Handler: These are usually the functions used to handle calls directed to an endpoint.
Let's try to write a simple server in Go that receives a ping request and sends back a response to its caller.
Creating an HTTP server without any framework
We'll start with a very simple request, which doesn't involve processing any query or path parameter. For this, we'll directly use Go's built-in net/http package. This package provides a basic server and client implementation.
In the below code snippet, we have tried to ...
package mainimport ("net/http""fmt""io")func main() {http.HandleFunc("/ping", ping)fmt.Println("Starting the server at port 8081")err := http.ListenAndServe(":8081", nil)if err != nil {fmt.Println("Error while starting the server ", err)}}func ping(w http.ResponseWriter, r *http.Request) {fmt.Println("Got a ping")io.WriteString(w, "Welcome to the Coffeeshop!\n")}
Let's see what's happening above:
In line 10, we use the
HandleFuncfunction to define our endpoint. It takes the first argument as the endpoint, which is"\ping", and the second argument as the handler function,ping.The handler function
pingis defined in line 19. All handler functions have two arguments.The first is
http.ResponseWriter. TheresponseWriterinterface has a write method, which is used by the net/http package to form a response. It then sends this response back to the connection.The second is
http.Request. When a request hits an endpoint, the net/http package marshals it into an object of typehttp.Request. This can be used to access information like query parameters and request body.
Our
pingfunction is pretty simple: in line 20, it prints that it received a request and writes back a response in line 21 using theresponseWriterobject namedw.Back in the
mainfunction, we start our server at line 13. Once started, it will listen on port8081for any incoming requests.
On running this code, the server starts locally, prints "Starting the server at port 8081" on the terminal, and waits for requests on localhost:8081 .
Testing it
In order to test the code above, we need to send requests to the server with the endpoint URLs. This can be done with a tool like a cURL quite easily. If we use the same system, the command to hit the ping endpoint would be: