Developing a Practical Basis: Starting a Simple RESTful API Server
Setting Up a Simple RESTful API Server
In this section, we will cover the basics of setting up a simple RESTful API server using the Go programming language. We will explore the Gin framework, which is a lightweight and high-performance framework for building web applications.
Choosing a RESTful Web Framework
To write a RESTful-style API server, we need a RESTful web framework. After researching various options, I chose Gin due to its high performance, scalability, and stability. Gin is a relatively simple framework that is well-suited for building web applications.
Loading Routes and Starting the HTTP Service
The main.go file is the entry point for our Go program. In this file, we create a Gin engine and load routes using the router.Load() function. We also start the HTTP service using http.ListenAndServe().
Written Entry Function
Here is the main() function from the main.go file:
package main
import (
"log"
"net/http"
"apiserver/router"
"github.com/gin-gonic/gin"
)
func main() {
// Create the Gin engine
g := gin.New()
// Gin middlewares
middlewares := []gin.HandlerFunc{}
// Routes
router.Load(
// Cores
g,
// Middlewares
middlewares,
)
log.Printf("Start to listening the incoming requests on http address: %s", ":8080")
log.Printf(http.ListenAndServe(":8080", g).Error())
}
Loading Routes
To load routes, we call the router.Load() function, which loads the routing function from the router/router.go file. The routing function is responsible for mapping URLs to handlers.
API Server Health Status Self-Test
To ensure that the API server is running correctly, we added a self-test program that pings the server at regular intervals. If the server fails to respond, the program terminates.
Here is the pingServer() function:
func pingServer() error {
for i := 0; i < 10; i++ {
// Ping the server by sending a GET request to `/health`.
resp, err := http.Get("http://127.0.0.1:8080/sd/health")
if err == nil && resp.StatusCode == 200 {
return nil
}
// Sleep for a second to continue the next ping.
log.Print("Waiting for the router, retry in 1 second.")
time.Sleep(time.Second)
}
return errors.New("Can not connect to the router.")
}
Compiling Source Code
To compile the source code, we use the following commands:
$ cd $GOPATH/src/apiserver
$ git clone https://github.com/lexkong/vendor
$ gofmt -w
$ go tool vet
$ go build -v
The compiled binary files are stored in the current directory, with the same name as the directory: apiserver.
API Testing with cURL
To test the API, we use the cURL tool, which is a standard Linux distribution tool. We can use cURL to send HTTP requests and verify the responses.
Here is an example of a cURL command:
$ curl -v -XPOST -H "Content-Type: application/json" http://127.0.0.1:8080/user -d '{"username": "admin", "password": "admin1234"}'
This command sends a POST request to the /user endpoint with a JSON payload.
Starting the API Server
To start the API server, we run the following command:
$ ./apiserver
This command starts the API server on port 8080.
Testing the API
To test the API, we can use the following commands:
$ curl -XGET http://127.0.0.1:8080/sd/health
OK
$ curl -XGET http://127.0.0.1:8080/sd/disk
OK - Free space: 16321MB (15GB) / 51200MB (50GB) | Used: 31%
$ curl -XGET http://127.0.0.1:8080/sd/cpu
CRITICAL - Load average: 2.39, 2.13, 1.97 | Cores: 2
$ curl -XGET http://127.0.0.1:8080/sd/ram
OK - Free space: 455MB (0GB) / 8192MB (8GB) | Used: 5%
These commands test the API by sending GET requests to the /health, /disk, /cpu, and /ram endpoints.
Conclusion
In this section, we covered the basics of setting up a simple RESTful API server using the Go programming language and the Gin framework. We explored the Gin framework, loaded routes, and started the HTTP service. We also added a self-test program to ensure that the API server is running correctly. Finally, we tested the API using the cURL tool.