6

When Mac first installs Gin, if there is a timeout error, you can learn from this blog to solve it:
After installation, you can start the following steps:


Similar to the previous blog, here we use the Gin framework to implement it first

Simplest backend service:

 package main

import "github.com/gin-gonic/gin"

func sayHello(c *gin.Context) {
    //函数会返回状态码是200,JSON格式的数据key是message,value是"Hello Golang",
    c.JSON(200, gin.H{
        "message": "Hello Golang~",
    })
}
func main() {
    //创建默认的路由引擎
    r := gin.Default()
    //用户发送GET请求的时候,会触发sayhello这个函数
    r.GET("/hello", sayHello)
    //在9090端口启动服务
    r.Run(":9090")
}

Running the code, the result is as follows:


RestFul API

Restful API, simply put, is

  • Use GET request to query to get data;
  • Use POST requests to create data;
  • Use PUT request to update data;
  • Delete data with DELETE request

RestFul API development based on Gin framework

Here, since the browser can only send GET and POST requests, it is not convenient to test POST requests. We can download some tools (such as postman or apipost are free and easy to use, you can choose according to your own preferences).

The development of RestFul API based on the Gin framework is really convenient. The example code is as follows:

 package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

func sayHello(c *gin.Context) {
    //函数会返回状态码是200,JSON格式的数据key是message,value是"Hello Golang",
    c.JSON(200, gin.H{
        "message": "Hello Golang~",
    })
}
func main() {
    //创建默认的路由引擎
    r := gin.Default()
    //用户发送GET请求的时候,会触发sayhello这个函数
    r.GET("/hello", sayHello)

    r.GET("/book", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "method": "GET",
        })
    })
    r.POST("/book", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "method": "POST",
        })
    })
    r.PUT("/book", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "method": "PUT",
        })
    })
    r.DELETE("/book", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "method": "DELETE",
        })
    })
    //在9090端口启动服务
    r.Run(":9090")
}

Then enter go build in the terminal and press Enter, ./项目名字 Enter to start the service, you are done, you can happily debug in APIPOST:

Of course, the development of RestFul API based on the Gin framework is far more than that, and further introductions will be made in subsequent articles.


Reference: bilibili

LiberHome
409 声望1.1k 粉丝

有问题 欢迎发邮件 📩 liberhome@163.com