当前位置:网站首页>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 ")
}
边栏推荐
- C语言实例_2
- Amway wave C2 tools
- POJ 3177 Redundant Paths POJ 3352 Road Construction(双连接)
- Yunna | work order management software, work order management software app
- Typical problems of subnet division and super network construction
- Telnet,SSH1,SSH2,Telnet/SSL,Rlogin,Serial,TAPI,RAW
- What does security capability mean? What are the protection capabilities of different levels of ISO?
- Asset security issues or constraints on the development of the encryption industry, risk control + compliance has become the key to breaking the platform
- [chip scheme design] pulse oximeter
- Neon Optimization: an instruction optimization case of matrix transpose
猜你喜欢

shell脚本快速统计项目代码行数

Transformation transformation operator

Your cache folder contains root-owned files, due to a bug in npm ERR! previous versions of npm which

HMM notes

Typical problems of subnet division and super network construction

第三方跳转网站 出现 405 Method Not Allowed

HMM 笔记

Yunna | work order management measures, how to carry out work order management

mongodb查看表是否导入成功

MySQL script batch queries all tables containing specified field types in the database
随机推荐
【信号与系统】
How to evaluate load balancing performance parameters?
Yunna | work order management software, work order management software app
Transformation transformation operator
LeetCode:1175. Prime permutation
go-zero微服务实战系列(九、极致优化秒杀性能)
Case development of landlord fighting game
Yunna | work order management measures, how to carry out work order management
免费白嫖的图床对比
tansig和logsig的差异,为什么BP喜欢用tansig
Google发布安全更新,修复Chrome中已被利用的0 day
What does security capability mean? What are the protection capabilities of different levels of ISO?
The difference between Tansig and logsig. Why does BP like to use Tansig
shell脚本快速统计项目代码行数
Byte P7 professional level explanation: common tools and test methods for interface testing, Freeman
Sword finger offer II 035 Minimum time difference - quick sort plus data conversion
C语言实例_4
安全保护能力是什么意思?等保不同级别保护能力分别是怎样?
Neon Optimization: summary of performance optimization experience
WCF基金会