当前位置:网站首页>Gin introduction practice
Gin introduction practice
2022-07-07 01:36:00 【hualaoshuan】
A summary of this article :
1. Environment building 、 Thermal loading ;
- Chinese document :https://gin-gonic.com/zh-cn/docs/quickstart/
# download gin
cd ~/go/go-gin2
go get -u github.com/gin-gonic/gin
# If you can't download , Try
go env -w GO111MODULE=on
go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/,direct
# Project preparation ( Use go.mod Management project )
cd ~/go/go-gin2/gindemo01
go mod init gindemo01
# Compile the code after writing
go run main.go
# Third party hot loading
# file :https://github.com/gravityblast/fresh
export GOPROXY=https://goproxy.io
go get -u github.com/pilu/fresh
# fresh Put it in the project folder , Will generate... In the current directory tmp Catalog :
fresh
- file
~/go/go-gin2/gindemo01/main.go
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
// Create a default routing engine
r := gin.Default()
// Configure the routing
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, " value :%v", " Hello ")
})
// establish web service , Default 8080 port
r.Run(":8001")
}
2. The response data ;
- file
~/go/go-gin2/gindemo01/templates/index.html
<h1>{
{.title}}</h1>
- file
~/go/go-gin2/gindemo01/main.go
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
type Article struct {
Title string `json:"title"`
Desc string `json:"desc"`
Content string `json:"content"`
}
func main() {
// Create a default routing engine
r := gin.Default()
// Configure template path
r.LoadHTMLGlob("templates/*")
// Configure the routing
r.GET("/", func(c *gin.Context) {
// Return string
c.String(http.StatusOK, " value :%v", " home page ")
// return json
c.JSON(http.StatusOK, map[string]interface{
}{
"success" : true,
"msg": " complete ",
})
// The built-in method returns json
c.JSON(http.StatusOK, gin.H{
"success" : true,
"msg": " complete 2",
})
// Instantiate structure data
a := &Article{
" title ",
" Introduce ",
" Content ",
}
c.JSON(http.StatusOK, a)
// {"title":" title ","desc":" Introduce ","content":" Content "}
// return jsonp
// http://localhost:8001/?callback=12
c.JSONP(http.StatusOK, a)
// return xml
c.XML(http.StatusOK, gin.H{
"success" : false,
"msg": "xml",
})
// Rendering html
c.HTML(http.StatusOK, "index.html", gin.H{
"title" : " home page 1",
})
})
// establish web service , Default 8080 port
r.Run(":8001")
}
3. Routing values ;
- file
~/go/go-gin2/gindemo01/main.go
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
type UserInfo struct {
Username string `json:"username" form:"username"`
Passwd string `json:"passwd" form:"passwd"`
Age string `json:"age" form:"age"`
}
func main() {
// Create a default routing engine
r := gin.Default()
// obtain get Pass value
r.GET("/user", func(c *gin.Context) {
username := c.Query("username")
page := c.DefaultQuery("page","1")
// http://localhost:8001/user?username=hua
c.JSON(http.StatusOK, gin.H{
"username" : username,
"page": page,
})
})
// obtain " Forms " Of post Pass value
r.POST("/addUser", func(c *gin.Context) {
username := c.PostForm("username")
passwd := c.PostForm("passwd")
age := c.DefaultPostForm("age", "20")
c.JSON(http.StatusOK, gin.H{
"username" : username,
"passwd": passwd,
"age": age,
})
})
// Bind to structure
// http://localhost:8001/getUser?username=hua&passwd=123456
r.GET("/getUser", func(c *gin.Context) {
user := &UserInfo{
}
if err := c.ShouldBind(&user); err==nil {
fmt.Printf("%#v", user) // Print
c.JSON(http.StatusOK, user)
} else {
c.JSON(http.StatusOK, gin.H{
"err": err.Error(),
})
}
})
r.POST("/addUser2", func(c *gin.Context) {
user := &UserInfo{
}
if err := c.ShouldBind(&user); err==nil {
fmt.Printf("%#v", user) // Print
c.JSON(http.StatusOK, user)
} else {
c.JSON(http.StatusOK, gin.H{
"err": err.Error(),
})
}
})
// Dynamic routing
r.GET("/list/:cid", func(c *gin.Context) {
cid := c.Param("cid")
c.String(http.StatusOK, "%v", cid)
})
// establish web service , Default 8080 port
r.Run(":8001")
}
4. Routing grouping :

- file
~/go/go-gin2/gindemo01/routers/defaultRouters.go
package routers
import (
"github.com/gin-gonic/gin"
"net/http"
)
func DefaultRoutersInit (r *gin.Engine) {
defaultRouters := r.Group("/")
{
defaultRouters.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, " home page ")
})
}
}
- file
~/go/go-gin2/gindemo01/main.go
package main
import (
"gindemo01/routers"
"github.com/gin-gonic/gin"
)
func main() {
// Create a default routing engine
var r = gin.Default()
// Routing grouping
routers.DefaultRoutersInit(r)
// establish web service , Default 8080 port
r.Run(":8001")
}
5. Custom controller 、 Controller inheritance ;

- file
~/go/go-gin2/gindemo01/controllers/baseControllers.go
package _default
import (
"github.com/gin-gonic/gin"
"net/http"
)
type BaseController struct {
}
func (con BaseController) success (c *gin.Context) {
c.String(http.StatusOK, "ok")
}
func (con BaseController) error (c *gin.Context) {
c.String(http.StatusOK, "error")
}
- file
~/go/go-gin2/gindemo01/controllers/userControllers.go
package _default
import (
"github.com/gin-gonic/gin"
"net/http"
)
type UserController struct{
BaseController // Controller inheritance
}
func (con UserController) Index (c *gin.Context) {
c.String(http.StatusOK, " User list ")
}
func (con UserController) Add (c *gin.Context) {
c.String(http.StatusOK, " Add users ")
con.success(c)
}
- file
~/go/go-gin2/gindemo01/routers/defaultRouters.go
package routers
import (
_default "gindemo01/controllers/default"
"github.com/gin-gonic/gin"
"net/http"
)
func DefaultRoutersInit (r *gin.Engine) {
defaultRouters := r.Group("/")
{
defaultRouters.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, " home page ")
})
// User list
// UserIndex() Execution method , Without parentheses is the registration method
defaultRouters.GET("/user", _default.UserController{
}.Index)
// Add users
defaultRouters.GET("/user/add", _default.UserController{
}.Add)
}
}
6. Routing middleware ;

If used in middleware goroutine:
When in middleware or handler Start a new goroutine when , Out of commission The original context
c *gin.Context, Must use its read-only copyc.Copy()file
~/go/go-gin2/gindemo01/middlewares/init.go
package middlewares
import (
"fmt"
"github.com/gin-gonic/gin"
"time"
)
func InitMiddleware(c *gin.Context) {
fmt.Println(time.Now())
fmt.Println(c.Request.URL)
// Set up the data
c.Set("username", "zhang")
// Define the process statistics log
cc := c.Copy()
go func() {
time.Sleep(2 * time.Second)
fmt.Println("Done! in path " + cc.Request.URL.Path)
}()
}
- file
~/go/go-gin2/gindemo01/routers/defaultRouters.go
package routers
import (
"fmt"
_default "gindemo01/controllers/default"
"gindemo01/middlewares"
"github.com/gin-gonic/gin"
"net/http"
)
func DefaultRoutersInit (r *gin.Engine) {
defaultRouters := r.Group("/")
// Configure global middleware
defaultRouters.Use(middlewares.InitMiddleware)
{
defaultRouters.GET("/", func(c *gin.Context) {
// Get the data of middleware
username, _ := c.Get("username")
fmt.Println(username)
// Types of assertions
v, ok := username.(string)
if ok == true {
fmt.Println(" User name :" +v)
} else {
fmt.Println(" Failed to get user ")
}
c.String(http.StatusOK, " home page ")
})
// User list
// UserIndex() Execution method , Without parentheses is the registration method
defaultRouters.GET("/user", _default.UserController{
}.Index)
// Add users
defaultRouters.GET("/user/add", _default.UserController{
}.Add)
}
}
7. Customize Model;
About Model
If the application is very simple , Can be in Controller It handles common business logic . But if there is a function that you want to use in multiple controllers 、 Or reuse in multiple templates , The common functions can be extracted separately as a module (Model).Model It is a process of gradual abstraction , Usually in Model Encapsulate some public methods to make it different Controller Use , You can also smash Model To deal with data
file
~/go/go-gin2/gindemo01/models/tools.go
package models
import (
"time"
)
// Time into date
func UnixToTime(timestamp int) string {
t := time.Unix(int64(timestamp), 0)
return t.Format("2006-01-02 15:04:05")
}
- call :
time := models.UnixToTime(1653639435)
fmt.Println(" current time :"+time)
8. Session obtain :
Gin Not provided session Related documents , Need a third party session Middleware to achieve
Installation mode :
go get github.com/gin-contrib/sessionsfile
~/go/go-gin2/gindemo01/main.go
package main
import (
"gindemo01/routers"
"github.com/gin-contrib/sessions/redis"
"github.com/gin-gonic/gin"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
)
func main() {
// Create a default routing engine
var r = gin.Default()
// To configure session middleware
// Create based on cookie Storage engine for ,secret The parameter is the secret key used for encryption
store := cookie.NewStore([]byte("secret"))
// To configure session middleware ,store Is the storage engine created earlier
r.Use(sessions.Sessions("mysession", store))
// To configure redis Storage engine
store_redis, _ := redis.NewStore(10, "tcp", "localhost:6379", "", []byte("secret"))
r.Use(sessions.Sessions("mysession_redis", store_redis))
// Routing grouping
routers.DefaultRoutersInit(r)
routers.ApiRoutersInit(r)
// establish web service , Default 8080 port
r.Run(":8001")
}
- file
~/go/go-gin2/gindemo01/controllers/default/userController.go
package _default
import (
"fmt"
"gindemo01/models"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"net/http"
)
type UserController struct{
BaseController // Controller inheritance
}
func (con UserController) Index (c *gin.Context) {
session := sessions.Default(c)
// Set expiration time, etc
session.Options(sessions.Options{
MaxAge: 3600 * 6,
})
// Set up session
session.Set("username1", "hua")
session.Save() // preservation
// obtain session
username := session.Get("username1")
c.String(http.StatusOK, "username=%v", username)
time := models.UnixToTime(1653639435)
fmt.Println(" current time :"+time)
c.String(http.StatusOK, " User list ")
}
func (con UserController) Add (c *gin.Context) {
c.String(http.StatusOK, " Add users ")
con.success(c)
}
9. Use GORM Operating the database ;
brief introduction
GORM yes golang One of the orm frame ,orm It is through the syntax of the instance object , The technology of completing the operation of relational database 、 Is the abbreviation of object mapping
file
~/go/go-gin2/gindemo01/models/core.go
package models
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var DB *gorm.DB
var err error
func init () {
// Reference resources https://github.com/go-sql-driver/mysql#dsn-data-source-name For more details
dsn := "root:[email protected](127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
})
if err != nil {
fmt.Println(err)
}
}
- file
~/go/go-gin2/gindemo01/models/user.go
package models
// Structure initial capital
// Corresponding to the data table name , For example, the table is user_info Structure is defined as UserInfo
// By default, the table name is the plural form of the interface body
type User struct {
Id int
Username string
Age int
Email string
AddTime string
}
// Modify the default table name of the structure , Configuration data sheet
func (User) TableName() string {
return "user"
}
- file
~/go/go-gin2/gindemo01/controllers/default/userController.go
package _default
import (
"gindemo01/models"
"github.com/gin-gonic/gin"
"net/http"
)
type UserController struct{
BaseController // Controller inheritance
}
func (con UserController) Index (c *gin.Context) {
user := []models.User{
} // Defining slices
//models.DB.Find(&user)
models.DB.Where("age>20").Find(&user)
c.JSON(http.StatusOK, gin.H{
"result" : user,
})
}
func (con UserController) Add (c *gin.Context) {
c.String(http.StatusOK, " Add users ")
con.success(c)
}
func (con UserController) Edit (c *gin.Context) {
c.String(http.StatusOK, " Modify the user ")
}
func (con UserController) Delete (c *gin.Context) {
c.String(http.StatusOK, " Delete user ")
}
边栏推荐
- Taro2.* applet configuration sharing wechat circle of friends
- 黑马笔记---异常处理
- 树莓派/arm设备上安装火狐Firefox浏览器
- Transplant DAC chip mcp4725 to nuc980
- mongodb查看表是否导入成功
- Typical problems of subnet division and super network construction
- Make Jar, Not War
- Taro applet enables wxml code compression
- 2022 Google CTF SEGFAULT LABYRINTH wp
- Gnet: notes on the use of a lightweight and high-performance go network framework
猜你喜欢

今日问题-2022/7/4 lambda体中修改String引用类型变量

Send template message via wechat official account

mongodb查看表是否导入成功

Appium基础 — Appium Inspector定位工具(一)

AcWing 1148. 秘密的牛奶运输 题解(最小生成树)

移植DAC芯片MCP4725驱动到NUC980

Yunna - work order management system and process, work order management specification

微信公众号发送模板消息

对C语言数组的再认识

Comparison of picture beds of free white whoring
随机推荐
2022 Google CTF SEGFAULT LABYRINTH wp
Go zero micro service practical series (IX. ultimate optimization of seckill performance)
Js逆向——捅了【马蜂窝】的ob混淆与加速乐
子网划分、构造超网 典型题
Neon Optimization: an optimization case of log10 function
curl 命令
从底层结构开始学习FPGA----FIFO IP的定制与测试
免费白嫖的图床对比
MySQL script batch queries all tables containing specified field types in the database
AcWing 345. 牛站 题解(floyd的性质、倍增)
分享一个通用的so动态库的编译方法
tansig和logsig的差异,为什么BP喜欢用tansig
系统休眠文件可以删除吗 系统休眠文件怎么删除
拖拽改变顺序
LeetCode:1175. Prime permutation
【信号与系统】
Neon Optimization: About Cross access and reverse cross access
AcWing 904. 虫洞 题解(spfa求负环)
How to manage distributed teams?
Your cache folder contains root-owned files, due to a bug in npm ERR! previous versions of npm which