golang Network framework gin usage
- 2020-09-16 07:31:56
- OfStack
golang native http library can easily implement 1 http server, but for complex web services, routing resolution, request parameter resolution, object return, etc., native api is not enough, and gin is a fully functional, high performance web network framework, especially suitable for the development of web api
hello world
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.New()
r.GET("/ping", func(c *gin.Context) {
c.String(200, "hello world")
})
r.Run() // listen and serve on 0.0.0.0:8080
}
All of gin's business logic is implemented in the func(c * gin.Context) function as shown in this hello world program, through which requests and returns are passed
Request parameter resolution
gin provides a rich way to get request parameters
(c *Context) Query(key string) string // To obtain GET parameter
(c *Context) QueryArray(key string) []string // To obtain GET Parameters of the array
(c *Context) DefaultQuery(key, defaultValue string) // To obtain GET Parameter and provide a default value
(c *Context) Param(key string) string // To obtain Param Parameters, similar to "/user/:id"
(c *Context) GetRawData() ([]byte, error) // To obtain body data
I don't recommend using any of these functions. I recommend using a structure to describe the request and using bind api to get the request parameters directly
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"), // Header field cannot bind Can be passed GetHeader To obtain
}
// In the request Param Parameter fills in the structure uri field
if err := c.BindUri(req); err != nil {
return nil, nil, http.StatusBadRequest, fmt.Errorf("bind uri failed. err: [%v]", err)
}
// GET Request in Query Parameters of the filling form field
// non GET The request will be body In the json or xml Deserialize and populate form field
if err := c.Bind(req); err != nil {
return nil, nil, http.StatusBadRequest, fmt.Errorf("bind failed. err: [%v]", err)
}
http client ip 1 generally in the request header X-ES44en-ES45en and ES46en-ES47en-ES48en, gin provides (c *Context) ClientIP() string to obtain ip
Returns the inclusions
(c *Context) String(code int, format string, values ...interface{}) // return 1 A string
(c *Context) JSON(code int, obj interface{}) // return 1 a json
(c *Context) Status(code int) // return 1 A status code
File upload and return
Gets the file from the request
fh, err := ctx.FormFile("file")
if err != nil {
return err
}
src, err := fh.Open()
if err != nil {
return err
}
defer src.Close()
Returns the file
(c *Context) File(filepath string)
cros cross-domain
Server returns a field in the head "Access - Control - Allow - Origin", if the fields and request the domain is different, the browser will be browser refused, in fact, the place I understand should be no access to the client, the server should not return a result, the browser that the result is not available, so prompt cross-domain error, but the header fields also can write an address, or write *, is open to all sites, want to multiple website development, we can according to the request of "Origin" field, Dynamically set the "ES79en-ES80en-ES81en-ES82en" field to satisfy the permission to set the "Origin" field in the request, gin has a plug-in github. com/ gin-ES88en /cors is designed to do this, you can set multiple websites in AllowOrigins, you can also set the wildcard (to set AllowWildcard as true)
import "github.com/gin-contrib/cors"
r := gin.New()
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"a.example.com", "b.example.com"},
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,
}))
cookies
// maxAge Is the expiration time
// domain Is the address of a website, if Shared across domains cookie , can be set to a domain name,
// Such as a.example.com and b.example.com That can be domain Set to example.com
// secure for https Set to true . http Set to false
// httpOnly Set to false , otherwise, axios Is not available cookie
(c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)
In addition, axios needs to be set to withCredentials: true cookie to return normally
link
github address: https: / / github com/gin - gonic/gin
Code examples: https: / / github com hpifu/tpl go -- http