gin

1.helloworld

package main

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

func main(a) {
	engine := gin.Default()
	engine.GET("/hello".func(context *gin.Context) {
		context.Writer.Write([]byte("hello"))
	})

	engine.Run(": 8090")}Copy the code

Handle requests

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
)

func main(a) {
	engine := gin.Default()
	engine.Handle("GET"."/hello".func(context *gin.Context) {
		fmt.Println(context.FullPath())
		fmt.Println(context.Request.URL)
		fmt.Println(context.Request.Method)
		context.Writer.WriteString("hello world")})/ / GET a GET request to http://127.0.0.1:8090/demo? name=wanghaha&age=24
	engine.Handle("GET"."/demo".func(context *gin.Context) {
		fmt.Println(context.FullPath())
		name := context.DefaultQuery("name"."wang")
		age := context.Query("age")

		fmt.Println(name, age)
		context.Writer.WriteString(fmt.Sprintf("name:%v, age:%v", name, age))
	})

	// Get the POST request
	engine.Handle("POST"."/demoPost".func(context *gin.Context) {
		fmt.Println(context.FullPath())
		username := context.PostForm("username")
		password := context.PostForm("password")

		fmt.Println("username:", username)
		fmt.Println("password:", password)

		context.Writer.WriteString(fmt.Sprintf("username: %v, password: %v", username, password))
	})

	err := engine.Run(": 8090")
	iferr ! =nil {
		log.Fatal(err)
	}
}
Copy the code

GET, POST, DELETE, etc

package main

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

func main(a) {
	engine := gin.Default()
	engine.GET("/hello".func(context *gin.Context) {
		name := context.Query("name")
		context.Writer.WriteString(name)
	})

	engine.POST("/login".func(context *gin.Context) {
		username := context.PostForm("username")
		password := context.PostForm("password")

		if username == "admin" && password == "111111" {
			context.Writer.WriteString("ok")}else {
			context.Writer.WriteString("username or password error")
		}
	})
	
	engine.DELETE("/delete_user/:id".func(context *gin.Context) {
		id := context.Param("id")
		context.Writer.WriteString(id)
	})

	engine.Run(": 8090")}Copy the code

The parameter binds the GET request

http://127.0.0.1:8090/hello?name=wanghaha&age=24&sex=1

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
)

func main(a) {
	engine := gin.Default()

	// The parameter binds the GET request
	engine.GET("/hello".func(context *gin.Context) {
		var user User
		err := context.ShouldBindQuery(&user)
		iferr ! =nil {
			log.Fatal(err)
		}

		fmt.Println(user.Name)
		fmt.Println(user.Age)
		fmt.Println(user.Sex)
		context.Writer.WriteString(user.Name)
	})

	err := engine.Run(": 8090")
	iferr ! =nil {
		log.Fatal(err)
	}
}

type User struct{
	Name string `form:"name"`
	Age int `form:"age"`
	Sex int `form:"sex"`
}
Copy the code

Parameter binds the POST request

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
)

func main(a) {
	engine := gin.Default()

	// The argument binds the POST request
	engine.POST("/testPost".func(context *gin.Context) {
		var user User
		err := context.ShouldBind(&user)
		iferr ! =nil {
			log.Fatal(err)
		}

		fmt.Println(user.Name)
		fmt.Println(user.Age)
		fmt.Println(user.Sex)
		context.Writer.WriteString(user.Name)
	})

	err := engine.Run(": 8090")
	iferr ! =nil {
		log.Fatal(err)
	}
}

type User struct{
	Name string `form:"name"`
	Age int `form:"age"`
	Sex int `form:"sex"`
}
Copy the code

Bind data in JSON format

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
)

func main(a) {
	engine := gin.Default()

	// Parameter binding POST, JSON format request
	engine.POST("/testPost".func(context *gin.Context) {
		var user User
		err := context.BindJSON(&user)
		iferr ! =nil {
			log.Fatal(err)
		}

		fmt.Println(user.Name)
		fmt.Println(user.Age)
		fmt.Println(user.Sex)
		context.Writer.WriteString(user.Name)
	})

	err := engine.Run(": 8090")
	iferr ! =nil {
		log.Fatal(err)
	}
}

type User struct{
	Name string `form:"name"`
	Age int `form:"age"`
	Sex int `form:"sex"`
}
Copy the code

Return JSON data

package main

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

func main(a) {
	engine := gin.Default()

	// Returns data in JSON format, the first way
	engine.GET("/".func(context *gin.Context) {
		context.JSON(200.map[string]interface{} {"code": 0."msg": "ok"."data": map[string]interface{} {"value": 25,}})})// Returns data in JSON format, the second way
	engine.GET("/t1".func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{
			"code": 0."msg": "ok",})})// Returns data in JSON format, the third way
	engine.GET("/t2".func(context *gin.Context) {
		context.JSON(200, Response{
			Code: 0,
			Msg:  "ok",
			Data: nil,
		})
	})

	engine.Run(": 8090")}// Customize the response structure
type Response struct{
	Code int
	Msg string
	Data interface{}}Copy the code

Return HTML & load static file

package main

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

func main(a) {
	engine := gin.Default()

	// Load the template file
	engine.LoadHTMLGlob("./templates/*")

	// Load the static file directory
	engine.Static("/static"."./static")

	engine.GET("/".func(context *gin.Context) {
		context.HTML(200."index.html".nil)
	})

	engine.GET("/home".func(context *gin.Context) {
		context.HTML(http.StatusOK, "home.html", gin.H{
			"title": "home page"."message": "hello world",
		})
	})

	engine.Run(": 8090")}Copy the code

templates/index.html

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <h1>index page</h1>
    <img src="/static/feng.jpg" alt="">
</body>
</html>
Copy the code

templates/home.html

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{.title}}</title>
</head>
<body>
    <h1>message: {{.message}}</h1>
</body>
</html>
Copy the code

Routing group

package main

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

func main(a) {
	engine := gin.Default()

	// Route grouping
	api := engine.Group("/api")

	// Get the user interface
	api.GET("/get_user/:id".func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{"id": context.Param("id")})})// Add a user interface
	api.POST("/add_user".func(context *gin.Context) {
		type User struct {
			Name string `form:"name"`
			Age int `form:"age"`
		}
		var user User
		iferr := context.ShouldBind(&user); err ! =nil {
			log.Fatal(err)
		}

		fmt.Printf("name: %v, age:%v\n", user.Name, user.Age)
		context.JSON(http.StatusOK, gin.H{
			"code": 0."msg": "ok",})})// Delete the user interface
	api.DELETE("/delete_user/:id".func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{"id": context.Param("id")})})if err := engine.Run(": 8090"); err ! =nil {
		log.Fatal(err)
	}
}
Copy the code

Let’s try another way of writing the function

package main

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

func main(a) {
	engine := gin.Default()

	// Route grouping
	api := engine.Group("/api")
	{
		// Get the user interface
		api.GET("/get_user/:id", GetUser)

		// Add a user interface
		api.POST("/add_user", AddUser)

		// Delete the user interface
		api.DELETE("/delete_user/:id", DeleteUser)
	}

	if err := engine.Run(": 8090"); err ! =nil {
		log.Fatal(err)
	}
}

// Get the user
func GetUser(context *gin.Context) {
	context.JSON(http.StatusOK, gin.H{"id": context.Param("id")})}// Add a user
func AddUser(context *gin.Context) {
	type User struct {
		Name string `form:"name"`
		Age int `form:"age"`
	}
	var user User
	iferr := context.ShouldBind(&user); err ! =nil {
		log.Fatal(err)
	}

	fmt.Printf("name: %v, age:%v\n", user.Name, user.Age)
	context.JSON(http.StatusOK, gin.H{
		"code": 0."msg": "ok"})},// Delete the user
func DeleteUser(context *gin.Context) {
	context.JSON(http.StatusOK, gin.H{"id": context.Param("id")})}Copy the code

The middleware

Global Use of middleware

package main

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

func main(a) {
	engine := gin.Default()

	// Use this middleware globally
	engine.Use(MiddlewareDemo())

	engine.GET("/hello".func(context *gin.Context) {
		context.String(http.StatusOK, "hello")
	})

	engine.GET("/test".func(context *gin.Context) {
		context.String(http.StatusOK, "test")})if err := engine.Run(": 8090"); err ! =nil {
		log.Fatal(err)
	}
}

// Custom middleware
func MiddlewareDemo(a) gin.HandlerFunc {
	return func(context *gin.Context) {
		fmt.Println(context.Request.URL)
		fmt.Println(context.Request.RequestURI)
		fmt.Println(context.FullPath())
		fmt.Println(context.Request.Host)
		fmt.Println(context.Request.UserAgent())
	}
}
Copy the code

A view function uses middleware

package main

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

func main(a) {
	engine := gin.Default()

	// Partial use of middleware
	engine.GET("/hello",MiddlewareDemo(), func(context *gin.Context) {
		context.String(http.StatusOK, "hello")
	})

	engine.GET("/test".func(context *gin.Context) {
		context.String(http.StatusOK, "test")})if err := engine.Run(": 8090"); err ! =nil {
		log.Fatal(err)
	}
}

// Custom middleware
func MiddlewareDemo(a) gin.HandlerFunc {
	return func(context *gin.Context) {
		fmt.Println(context.Request.URL)
		fmt.Println(context.Request.RequestURI)
		fmt.Println(context.FullPath())
		fmt.Println(context.Request.Host)
		fmt.Println(context.Request.UserAgent())
	}
}
Copy the code

Middleware next

package main

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

func main(a) {
	engine := gin.Default()

	// Partial use of middleware
	engine.GET("/hello",MiddlewareDemo(), func(context *gin.Context) {
		fmt.Println("I'm executing business code.")
		context.String(http.StatusOK, "hello")
	})

	engine.GET("/test".func(context *gin.Context) {
		context.String(http.StatusOK, "test")})if err := engine.Run(": 8090"); err ! =nil {
		log.Fatal(err)
	}
}

// Custom middleware
func MiddlewareDemo(a) gin.HandlerFunc {
	return func(context *gin.Context) {
		fmt.Println(context.Request.URL)
		fmt.Println(context.Request.RequestURI)
		fmt.Println(context.FullPath())
		fmt.Println(context.Request.Host)
		fmt.Println(context.Request.UserAgent())

		// Next will execute the business code
		context.Next()

		fmt.Println("I'm executing the view function after it's finished executing.")}}Copy the code