当前位置:网站首页>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 ")
}
边栏推荐
- THREE.AxesHelper is not a constructor
- 子网划分、构造超网 典型题
- 拖拽改变顺序
- MySQL script batch queries all tables containing specified field types in the database
- Neon Optimization: an instruction optimization case of matrix transpose
- Can the system hibernation file be deleted? How to delete the system hibernation file
- How to prevent overfitting in cross validation
- Taro 小程序开启wxml代码压缩
- Taro2.* 小程序配置分享微信朋友圈
- Sword finger offer II 035 Minimum time difference - quick sort plus data conversion
猜你喜欢

AcWing 361. 观光奶牛 题解(spfa求正环)

Send template message via wechat official account

tansig和logsig的差异,为什么BP喜欢用tansig

mongodb查看表是否导入成功

Start from the bottom structure to learn the customization and testing of fpga---- FIFO IP

如何管理分布式团队?

Dark horse notes - exception handling

2022 Google CTF SEGFAULT LABYRINTH wp

Make Jar, Not War

LeetCode. 剑指offer 62. 圆圈中最后剩下的数
随机推荐
Set up [redis in centos7.x]
Send template message via wechat official account
各种语言,软件,系统的国内镜像,收藏这一个仓库就够了: Thanks-Mirror
AcWing 1141. 局域网 题解(kruskalkruskal 求最小生成树)
hdu 4661 Message Passing(木DP&amp;组合数学)
Installation and testing of pyflink
Body mass index program, entry to write dead applet project
Taro2.* 小程序配置分享微信朋友圈
ClickHouse字段分组聚合、按照任意时间段粒度查询SQL
Meet in the middle
Today's question -2022/7/4 modify string reference type variables in lambda body
Transplant DAC chip mcp4725 to nuc980
LeetCode:1175. Prime permutation
Clickhouse fields are grouped and aggregated, and SQL is queried according to the granularity of any time period
table表格设置圆角
dvajs的基础介绍及使用
Go zero micro service practical series (IX. ultimate optimization of seckill performance)
公钥\私人 ssh避password登陆
Neon Optimization: an optimization case of log10 function
1123. 最深叶节点的最近公共祖先