The usage of gin in golang network framework


Golang native HTTP library can easily implement an HTTP server, but for complex web services, such as routing resolution, request parameter parsing, object return, etc., native API is not enough. Gin is a web network framework with complete functions and high performance, which is especially suitable for the development of Web API

hello world

package main

import ""

func main() {
  r := gin.New()
  r.GET("/ping", func(c *gin.Context) {
    c.String(200, "hello world")
  r.Run() // listen and serve on

As the Hello world program shows, all business logic of gin is in func (c* gin.Context )Function, request and return through this gin.Context transmit

Request parameter parsing

Gin provides rich ways to obtain request parameters

(c * context) query (key string) string // get get parameters
(c * context) queryarray (key string) [] string // get get parameter array
(c * context) defaultquery (key, DefaultValue string) // get the get parameter and provide the default value
(c * context) param (key string) string // get param parameter, similar to "/ user /: Id"
(c * context) getrawdata() ([] byte, error) // get body data

However, I do not recommend using these functions. It is recommended to use structure to describe the request, and then use the bind API to directly obtain the request parameters

type HelloWorldReq struct {
  Token  string `json:"token"`
  ID    int  `json:"id" uri:"id"`
  Email  string `json:"email" form:"email"`
  Password string `json:"password" form:"password"`

req := &HelloWorldReq{
  Token: c.getheader ("authorization"), // the header field cannot be bound and can be obtained through getheader

//Fill the URI field in the structure with the param parameter in the request
if err := c.BindUri(req); err != nil {
  return nil, nil, http.StatusBadRequest, fmt.Errorf("bind uri failed. err: [%v]", err)

//Fill the form field with the query parameter in the get request
//For non get requests, the form field is filled after the JSON or XML in the body is deserialized
if err := c.Bind(req); err != nil {
  return nil, nil, http.StatusBadRequest, fmt.Errorf("bind failed. err: [%v]", err)

The client IP of HTTP is usually in the x-forward-for and x-real-ip of the request header. Gin provides (c * context) clientip() string to obtain the IP

Return to inclusion

(c * context) string (code, int, format, string, values... Interface {}) // returns a string
(c * context) JSON (code int, obj interface {}) // returns a JSON
(c * context) status (code int) // returns a status code

File upload and return

Get file from request

fh, err := ctx.FormFile("file")
if err != nil {
  return err

src, err := fh.Open()
if err != nil {
  return err
defer src.Close()

Return to file

(c *Context) File(filepath string)

Cross domain

There is a field in the header returned by the server “Access control allow origin”. If the field is different from the requested domain, the browser will be rejected by the browser. In fact, I understand that the client does not have permission to access, and the server should not return the result. The browser thinks that the result is not available, so it prompts a cross domain error, and the header field can only write an address, or write it as *, which is open to all websites. To develop multiple websites, we can dynamically set the “access control allow origin” field according to the “origin” field of the request. If the permission is satisfied, it must be set to the “origin” field in the request. There is a plug-in for gin -Contrib / CORS is specifically used to do this, which can be found in the allow origin You can also set wildcards (allowwildcard should be set to true)

import ""

r := gin.New()
  AllowOrigins:   []string{"", ""},
  AllowMethods:   []string{"PUT", "POST", "GET", "OPTIONS"},
  AllowHeaders:   []string{"Origin", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization", "Accept", "Cache-Control", "X-Requested-With"},
  AllowCredentials: true,


//Maxage is the expiration time
//Domain is the address of the website. If you want to share cookies across domains, you can set it as a domain name,
//For example, a  And B You can set the domain to
//Secure is set to true for HTTPS and false for HTTP
//Set httponly to false, otherwise libraries such as Axios will not be able to access the cookie
(c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)

In addition, Axios needs to set withcredentials: true cookie to return normally


GitHub address:
Code example:

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.

Recommended Today

Api: tiktok: user video list

Tiktok tiktok, tiktok, tiktok, Api, Api, jitter, voice, bullet screen comments, jitter, jitter, and jitter. Tiktok tiktok tiktok data, jitter data acquisition, live broadcast of shaking sound Titodata: professional short video data acquisition and processing platform. For more information, please contact:TiToData Massive data collection Collect 500 million pieces of data for customers every day Tiktok […]