当前位置:网站首页>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/sessions
file
~/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 ")
}
边栏推荐
- mysqlbackup 还原特定的表
- 公钥\私人 ssh避password登陆
- MySQL script batch queries all tables containing specified field types in the database
- [JS] obtain the N days before and after the current time or the n months before and after the current time (hour, minute, second, year, month, day)
- Start from the bottom structure to learn the customization and testing of fpga---- FIFO IP
- According to the analysis of the Internet industry in 2022, how to choose a suitable position?
- Send template message via wechat official account
- What are the differences between Oracle Linux and CentOS?
- 搭建【Redis in CentOS7.x】
- 设置Wordpress伪静态连接(无宝塔)
猜你喜欢
JS reverse -- ob confusion and accelerated music that poked the [hornet's nest]
Today's question -2022/7/4 modify string reference type variables in lambda body
Appium基础 — Appium Inspector定位工具(一)
Transformation transformation operator
[advanced C language] 8 written questions of pointer
云呐|工单管理软件,工单管理软件APP
如何管理分布式团队?
AcWing 1148. 秘密的牛奶运输 题解(最小生成树)
AcWing 345. 牛站 题解(floyd的性质、倍增)
The difference between Tansig and logsig. Why does BP like to use Tansig
随机推荐
Transformation transformation operator
Spark TPCDS Data Gen
图片打水印 缩放 和一个输入流的转换
Js逆向——捅了【马蜂窝】的ob混淆与加速乐
Taro2.* 小程序配置分享微信朋友圈
Metauniverse urban legend 02: metaphor of the number one player
黑马笔记---创建不可变集合与Stream流
ClickHouse字段分组聚合、按照任意时间段粒度查询SQL
云呐|工单管理软件,工单管理软件APP
What does front-end processor mean? What is the main function? What is the difference with fortress machine?
Can the system hibernation file be deleted? How to delete the system hibernation file
7.6 simulation summary
hdu 4661 Message Passing(木DP&amp;组合数学)
Match VIM from zero (0) -- Introduction to vimscript
AcWing 1140. 最短网络 (最小生成树)
域分析工具BloodHound的使用说明
C语言实例_4
修改px4飞控的系统时间
如何管理分布式团队?
C # method of calculating lunar calendar date 2022