当前位置:网站首页>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 ")
}
边栏推荐
- Make Jar, Not War
- 454-百度面经1
- Start from the bottom structure to learn the customization and testing of fpga---- FIFO IP
- Comparison of picture beds of free white whoring
- Taro 小程序开启wxml代码压缩
- docker 方法安装mysql
- 前置机是什么意思?主要作用是什么?与堡垒机有什么区别?
- json学习初体验–第三者jar包实现bean、List、map创json格式
- AcWing 1142. 繁忙的都市 题解(最小生成树)
- [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)
猜你喜欢
Dark horse notes - exception handling
AI automatically generates annotation documents from code
Today's question -2022/7/4 modify string reference type variables in lambda body
子网划分、构造超网 典型题
MySQL script batch queries all tables containing specified field types in the database
Installation of gazebo & connection with ROS
Yunna - work order management system and process, work order management specification
第三方跳转网站 出现 405 Method Not Allowed
今日问题-2022/7/4 lambda体中修改String引用类型变量
mongodb查看表是否导入成功
随机推荐
免费白嫖的图床对比
Clickhouse fields are grouped and aggregated, and SQL is queried according to the granularity of any time period
前置机是什么意思?主要作用是什么?与堡垒机有什么区别?
HMM notes
THREE. AxesHelper is not a constructor
C language instance_ four
POJ 3177 Redundant Paths POJ 3352 Road Construction(双连接)
Installation and testing of pyflink
Gnet: notes on the use of a lightweight and high-performance go network framework
拖拽改变顺序
Add the applet "lazycodeloading": "requiredcomponents" in taro,
Google released a security update to fix 0 days that have been used in chrome
Sword finger offer II 035 Minimum time difference - quick sort plus data conversion
ZOJ Problem Set – 2563 Long Dominoes 【如压力dp】
Send template message via wechat official account
从底层结构开始学习FPGA----FIFO IP的定制与测试
MySQL script batch queries all tables containing specified field types in the database
增加 pdf 标题浮窗
C语言实例_5
2022 Google CTF segfault Labyrinth WP