Gin brief introduction

Guide package

import "github.com/gin-gonic/gin"
Copy the code

Creating a Routing Engine

func main(){
    r:=gin.Default()
}
Copy the code

Configure the routing

Invokes the following callback function when requesting the address of the first argument. The subsequent callback has an argument of type gin.Context. So once we get this parameter we can use this parameter to return something to the client

R. gutierrez ET ("/", the func (c * gin in the Context) {c.s. tring (200, value: "" % v", "hello gin")})Copy the code

Start the gin

Once the routing configuration is complete, we can start the GIN framework

R.run ()// Start a Web service starts on port 0.0.0.0:8080 by defaultCopy the code

Run with a specified port number

R.run (:8000)// This indicates that the project can be run on port 8000Copy the code

HTTP method description

  • Get is used to get data from the server
  • Post is used to submit data to the server
  • Put Modifies server data
  • Delete Deletes data

Returns the status code in the HTTP package

The HTTP package defines a lot of status codes for server requests. At this point we can use the HTTP status code to return to the client for example: the above 200 we can replace with the following literal constant

http.StatusOK
Copy the code

The return type

Return string

R. gutierrez ET ("/", the func (c * gin in the Context) {c.s. tring (200, value: "" % v", "home page")})Copy the code

Returns a json

R.et ("/json",func(c *gin.Context){c.json (200,map[string]interface{}{"success":true, "MSG ":" hello ", R. gutierrez ET})}) / / 2 ("/json ", func (c * gin in the Context) {SAN Antonio son (200, gin. H {" success ": true," MSG ":" hello ", Type Artile struct{Title string Desc string Content string} Title: "I am a Title, Desc:" I am a description ", Content: "I am a Content"} / / r. gutierrez ET - using structure return ("/json ", a)})Copy the code

Customize key values using structure tags when returning JSON

To do this, you need to modify the structure to add the structure tag

type Artile struct{
    Title string `json:"title"`
    Desc  string `json:"desc"`
    Content string `json:"content"`
}
Copy the code

Return the json

JsonP by default returns the same response data as JSON, but what if the client requests it? Callback = XXX, default return XXX ({title:””,desc:””,content:””}), used to solve cross-domain problems.

c.JSONP()
Copy the code

Return XML data

The parameters put in XML are returned in the same way as the parameters returned in JSON, with structures and maps returned

c.XML()
Copy the code

Return the rendered template (return the web page containing the server data)

  1. Load the template before configuring the route
R :=gin.Default() r.loadhtmlglob ("templates/*")// Load the templates. This means loading all tier 1 templates and subfolder templates under TemplatesCopy the code
  1. Return to HTML template
R. gutierrez ET ("/new ", the func (c * gin in the Context) {c. HTML (200, "news. The HTML", the map [string] interface {} {" title ":" I am a template data ", "MSG" : "hello", R. gutierrez ET})}) ("/new ", the func (c * gin in the Context) {c. HTML (200, "news. The HTML", gin. H {" title ":" I am a template data ", "MSG" : "hello,"})})Copy the code
  1. Define the template
<! {{define "default/index.html"}} <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{.title}}</title> </head> <body> {{.content}} </body> </html> {{ end }}Copy the code

When using this template we write the template name as default/index.html as defined here

Template data manipulation

The output data

Output background data in the template

{{.name}}
Copy the code

Write the name of the key passed from the background after

Define variables

1. Define the variable t and assign the data in title to it

{{$t :=.title}}Copy the code

2. Use variables

{{$t}}
Copy the code

Remove the blank space

Sometimes when using template syntax it is unavoidable to introduce whitespace and line breaks so that the template will render something different from what we expected. Use the {{- syntax to remove all whitespace on the left side of the template content, and use the -}} syntax to remove all whitespace on the right side of the template content:

{{- .name -}}
Copy the code

The comparison function

  1. Boolean functions treat any type of zero value as false and the rest as true. The following is a collection of binary comparison operations defined as functions
The operator explain
eq Return true if arg1==arg2
ne If arg1! =arg2 returns true
lt Returns true if arg1<arg2
le Returns true if arg1<=arg2
gt Returns true if arg1>arg2
ge Returns true if arg1>=arg2
  1. Example:

if-else

{{if gt. Score 60}} < / p > < p > to pass the failed the {{else}} < p > < / p > {{end}}Copy the code

if-else-if

{{if gt. Score 90}} < / p > < p > to pass the {{else if gt. Score 80}} < / p > < p > good {{else if gt. Score 60}} < / p > < p > to pass the {{end}}Copy the code

range

The template syntax of Go uses the range keyword for traversal, which can be written in the following two ways, where the value of pipeline must be array, slice, dictionary or channel.

If the pipeline value has a length of 0, there is no output

{{range $key,$value := .obj}}
    {{$value}}
{{end}}
Copy the code

If the pipeline value has a length of 0, output T0

{{range $key, $value: = the. Obj}} {{$value}} {{else}} pipeline the value of the length of 0 {{end}}Copy the code

eg:demo1

<ul>
{range $key,$value := .newsList}
    <li>{{$key}} ----- {{$value}}</li>
{{end}}
</ul>
Copy the code

Possible: nested loops eg:demo2

< ul > {range $key, $value: = the newsList} < li > {{$key}} - {{$value}} < / li > {{else}} < li > there is no data in the list < / li > {{end}} < / ul >Copy the code

With deconstruction

Deconstruct the attributes of the object and use them directly in the template

Before use with

<h4>{{.user.Name}}<h4>
<h4>{{.user.Age}}<h4>
<h4>{{.user.Gender}}<h4>
Copy the code

After use with

{{with. User}} < h4 > Name: {{. Name}} < / h4 > < h4 > Age: {{. Age}} < / h4 > < h4 > Gender: {{. Gender}} < / h4 > {{end}}Copy the code

Predefined template functions

When templates are executed, functions are looked up in two function dictionaries: first, the template function dictionary, and then the global function dictionary. Instead of defining functions in a template, the funcs method is used to add functions to the template.

Predefined global functions are as follows:

The function name explain
and ??
or ??
not Returns the negation of the Boolean type of its single argument
len Returns the integer type length of its argument
index ??
Calls a child of a predefined function
` ` `
// Use global functions. Find the length of the.title variable
{{len .title}}
` ` `
#### Custom template functions
  1. Customize a function
Func UnixToTime(timestamp int) string{t:=time.Unix(int64(timestamp),0) return t.fromat ("2006-01-01 03:04:05 ")}Copy the code
  1. Inject functions into the framework

Call R.setfuncMap before the template loading method (R.loadhtmlglob) to inject the custom function into the map

r.SetFuncMap(template.FuncMap{
    "UnixToTime":UnixToTime,
}

)
Copy the code
  1. Use of custom template functions in templates
{{unixtotime. date}} // Where. Date is the function parameterCopy the code

Nested template

  1. Create a public folder in the Templates folder to hold your public templates
  2. Create page_head.html in the public folder
  3. Edit common header
{{ define "public/page_header.html" }} <style> h1{ background:#ff0000; text-align:center; } </style> <h1> I am a public title </h1> {{end}}Copy the code
  1. Externally load this template

// Pay attention to the following. Pass the current page’s data to page_header

{{ template "default/page_header.html" .}}
Copy the code

Static file service

When we render HTML files that reference static files, we need to configure the static Web service r.static (“/static”,”./static”) with /static before it for the route and./static after it for the path

Func main(){r:=gin.Default() // Configure the static Web service, the first parameter indicates the route, the second parameter indicates the path r.static ("/static",".Copy the code

Create the path project root directory /static/ CSS /base.css

  1. The CSS is imported into the template
<link rel="stylesheet" href="static/css/base.css">
Copy the code

Get Post and Get the Get Post value

Get Requests to transfer values

GET /user? uid=20&page=1

Router.get ("/user",func(CTX *gin.Context){// No default value uid:= ctx.query ("uid") // Default value page sent from request page:=ctx.QueryDefault("page","0") ctx.String(200,"uid = %v page = %v",uid,page) })Copy the code

Post Requests to transfer values

  1. The user gets a page with a form from the server through an ordinary request.
The router. The Get ("/user ", func (CTX * gin. The Context) {c. HTML (HTTP. StatusOK, "template", gin. H {})})Copy the code
  1. Define a form form in the template

  1. Define the route on the server as/doAddUserThe POST method corresponds to the pSOT request from the client.

Gets the data binding passed by Get and Post to the structure

  1. Defining structure

  1. The request data is bound to the structure in the same way as get-POST

Get the XML data posted by the client

  1. Defining structure

  1. Convert the JSON string into a structure

  1. Retrieve the XML data that has been posted and transform it into a structure

Dynamic routing of values

Routing group

  1. Foreground routing group

  1. API interface routing group

  1. The background manages routing groups

The route file is removed

Create a file manager folder for the routers and place the files to be grouped in this folder

  1. Create the AdminRouters. Go file and define the AdminRoutersInit(R *gin.Engine) method

  1. The change of the main

The controller file is removed

  1. Create directories

controllers

-admin - > create userController.go - API - IELTSCopy the code
  1. Write the corresponding method

  1. Use controller

Controller inheritance

  1. Binds controller – dependent methods to an empty structure

  1. Use it in main

  1. Define the base class controller

  1. Inherit the base class controller

After inheritance, we can use the controller methods defined by the parent class in the controller methods.

GIN middleware details

Generally speaking: middleware is a series of operations completed before and after routing matching. Gin framework allows developers to add their own hook functions to the process of processing requests. This hook function is called middleware, which is suitable for handling common business logic such as login authentication, permission verification, data paging, logging, time statistics, etc.

Defining middleware

  1. Definition of middleware

Where the code before c.ext () is executed before the route call, and the code after the route call is completed.

  1. Use of middleware (middleware can write more than one)

  1. Write multiple middleware

Execution order, first middleware output 1-> Next -> second middleware output 1-> Next -> Routing methods -> second middleware output 2-> first middleware output 2

A method that terminates the execution of routes behind middleware

Write the following method in the middleware

c.Abort()
Copy the code

Global middleware

The global middleware can also be configured with multiple configurations

Middleware extraction

The root directory is created as middlewares

- init.go
Copy the code

Routing packet middleware

(Middleware – middleware) (Middleware controllers share data)

  1. Set values in the middleware

  1. Gets the value from the controller

Matters needing attention

  1. Default Middleware issues

2. Problems of using coroutines in middleware

Gin defines common modules

The new directory

modules

- tools.go
Copy the code

Just extract the method under the class in the Modules folder. Methods defined here can be imported and used anywhere.

Gin file upload

Uploading a single file is basically the same as uploading multiple files with different file names

  1. Define the form

  1. Define the controller to handle form submission content

Upload multiple files with the same file name

  1. Define the form

  1. Define the controller to handle multiple file uploads

Gin setting cookies

  1. Set the Cookie

  1. To get a Cookie

  1. Delete the Cookie

To delete cookies, you only need to set the Cookie expiration time to -1. Or the value of the original Cookie can be overwritten by resetting the Cookie.

  1. Cookies are domain-based. Cookies cannot be accessed in different domains.

How do multiple secondary domain names share cookies

When multiple secondary domain names share cookies, you only need to leave the first few digits of the domain name blank, for example, a.baidu.com and b.baidu.com. You can set cookies to.baidu.com

Gin in the Session

Gin Session Middleware

Store Session to Cookie

Store sessions to the Redis database

The knowledge about the MSYQL database to be filled

GORM is used to operate MySql databases in Gin

GORM official address or GORM official Address Chinese version

Function is introduced

1. Connect to the database

2. Define the model that operates on the database table

It is recommended that you define a model with the same name as the table. Fields are recommended to be consistent with database fields

2. Query the database

SQL > select * from db where SQL > select * from DB where SQL > select * from DB where SQL > select * from DB where

4. Insert data

5. Modify data

  • Method 1

  • Method 2

  • Methods 3

Delete the data

  • Method 1

  • Way 2