当前位置:网站首页>Go's gin framework learning
Go's gin framework learning
2022-04-23 17:52:00 【Liu Yuanshan】
Frame installation
1、 Setting agent
In the download gin Before frame , We also need to configure go Public proxy image , The purpose is to solve github Unable to access or slow access , stay cmd Execute command in window :
# Here I set it to automatic mode ,on After I started the mode of, I couldn't execute it inexplicably gin The code download
go env -w GO111MODULE=auto
# Setting agent
go env -w GOPROXY=https://goproxy.io,direct
2、 download gin frame
go get -u github.com/gin-gonic/gin
3、 establish demo project , function gin frame
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
router.GET("/", func(context *gin.Context) {
context.String(http.StatusOK, "HelloWorld")
})
router.Run(":3333")
}
4、 Lack of package error handling
Because of the Internet , Here and google Related packages are inaccessible , Need to download separately
..\github.com\go-playground\universal-translator\errors.go:7:2: cannot find package "github.com/go-playground/locales" in any of:
C:\Program Files\Go\src\github.com\go-playground\locales (from $GOROOT)
D:\go_work\src\github.com\go-playground\locales (from $GOPATH)
..\github.com\go-playground\validator\baked_in.go:23:2: cannot find package "github.com/leodido/go-urn" in any of:
C:\Program Files\Go\src\github.com\leodido\go-urn (from $GOROOT)
D:\go_work\src\github.com\leodido\go-urn (from $GOPATH)
..\github.com\gin-gonic\gin\logger.go:14:2: cannot find package "github.com/mattn/go-isatty" in any of:
C:\Program Files\Go\src\github.com\mattn\go-isatty (from $GOROOT)
D:\go_work\src\github.com\mattn\go-isatty (from $GOPATH)
..\github.com\gin-gonic\gin\binding\msgpack.go:15:2: cannot find package "github.com/ugorji/go/codec" in any of:
C:\Program Files\Go\src\github.com\ugorji\go\codec (from $GOROOT)
D:\go_work\src\github.com\ugorji\go\codec (from $GOPATH)
..\github.com\go-playground\validator\baked_in.go:20:2: cannot find package "golang.org/x/crypto/sha3" in any of:
C:\Program Files\Go\src\golang.org\x\crypto\sha3 (from $GOROOT)
D:\go_work\src\golang.org\x\crypto\sha3 (from $GOPATH)
..\github.com\gin-gonic\gin\gin.go:19:2: cannot find package "golang.org/x/net/http2" in any of:
C:\Program Files\Go\src\golang.org\x\net\http2 (from $GOROOT)
D:\go_work\src\golang.org\x\net\http2 (from $GOPATH)
..\github.com\gin-gonic\gin\gin.go:20:2: cannot find package "golang.org/x/net/http2/h2c" in any of:
C:\Program Files\Go\src\golang.org\x\net\http2\h2c (from $GOROOT)
D:\go_work\src\golang.org\x\net\http2\h2c (from $GOPATH)
..\github.com\go-playground\validator\baked_in.go:21:2: cannot find package "golang.org/x/text/language" in any of:
C:\Program Files\Go\src\golang.org\x\text\language (from $GOROOT)
D:\go_work\src\golang.org\x\text\language (from $GOPATH)
..\github.com\gin-gonic\gin\binding\protobuf.go:12:2: cannot find package "google.golang.org/protobuf/proto" in any of:
C:\Program Files\Go\src\google.golang.org\protobuf\proto (from $GOROOT)
D:\go_work\src\google.golang.org\protobuf\proto (from $GOPATH)
Compilation finished with exit code 1
1) stay GOPATH The directory src Under the table of contents , New folder google.golang.org, then cmd Window , Switch to the directory , Carry out orders :
Notice that it's not github.com Under the table of contents , It is src Under the table of contents
D:\go_work\src\google.golang.org
git clone https://github.com/protocolbuffers/protobuf-go.git
When the download is complete , take protobuf-go Rename the directory to protobuf

2) Because of the Internet , Here and golang.org Related packages cannot be downloaded
stay GOPATH The directory src Under the table of contents , New folder golang.org, then cmd Window , Switch to the directory , Carry out orders :
Notice that it's not github.com Under the table of contents , It is src Under the table of contents
D:\go_work\src\golang.org
git clone https://github.com/golang/tools.git
When the download is complete , take tools Rename the directory to x

3) Get into x Catalog , Go ahead with the order :
D:\go_work\src\golang.org\x
git clone https://github.com/golang/crypto.git
4) Install as required github.com Missing package
1、 Get into D:\go_work\src\github.com\go-playground Under the table of contents
git clone https://github.com/go-playground/locales.git
2、 Get into D:\go_work\src\github.com\leodido Under the table of contents
git clone https://github.com/leodido/go-urn.git
3、 Get into D:\go_work\src\github.com\mattn Under the table of contents
git clone https://github.com/mattn/go-isatty.git
4、 Get into D:\go_work\src\github.com\ugorji Under the table of contents
Wrong presentation :cannot find package “github.com/ugorji/go/codec” in any of:
git clone https://github.com/ugorji/go.git
5、 Get into D:\go_work\src\golang.org\x Under the table of contents , The lack of net package
Wrong presentation :cannot find package “golang.org/x/net/http2” in any of:
cannot find package “golang.org/x/net/http2/h2c” in any of:
git clone https://github.com/golang/net.git
6、 Get into D:\go_work\src\golang.org\x Under the table of contents , The lack of text package
Wrong presentation :cannot find package “golang.org/x/text/language” in any of:
cannot find package “golang.org/x/text/secure/bidirule” in any of:
git clone https://github.com/golang/text.git
Successfully started the service
visit :http://127.0.0.1:3333/


Use of simple routing
gin Your route comes from httprouter library , therefore httprouter Functions gin Also has the
actual combat
Code :
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
// initialization router
router := gin.Default()
// Define the path , Use a colon : Instead of variables
router.GET("/user/:name/:age", func(context *gin.Context) {
// obtain name value
name := context.Param("name")
age := context.Param("age")
message := name + " is " + age
// Return value
context.String(http.StatusOK, "hello %s", message)
})
router.Run()
}
visit
http://127.0.0.1:8080/user/user11/18
Get Request to use
1、context.DefaultQuery Set the default value when the value cannot be obtained
2、context.Query Direct value
Code
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
// initialization router
router := gin.Default()
// Define the path
router.GET("/user/", func(context *gin.Context) {
// obtain name value
name := context.DefaultQuery("name"," The default value is ")
age := context.Query("age")
message := name + " is " + age
// Return value
context.String(http.StatusOK, "hello %s", message)
})
router.Run()
}
visit
http://127.0.0.1:8080/user/?name=user1&age=18
Post Request to use
Common scenes
1、application/json (request Sent in json data , use post Mode sending Content-type use application/json)
2、application/x-www-form-urlencode ( Common form submission , hold query_string Put the content of body in vivo , Also need to urlencode)
3、application/xml (http As a transport protocol ,xml As a coding method, remote call specification )
4、multipart/form-data( File transfer )
Code
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
// initialization router
router := gin.Default()
// Definition POST Method path
router.POST("/form_post", func(context *gin.Context) {
// Get the value passed
name := context.PostForm("name")
age := context.DefaultPostForm("age","10")
// With JSON Format return
context.JSON(http.StatusOK, gin.H{
"status":gin.H{
"status_code":http.StatusOK,"status":"ok"},"name":name,"age":age})
})
router.Run()
}
Access and return results
D:\go_work\src>curl -X POST http://127.0.0.1:8080/form_post -H “application/x-www-form-urlencode” -d “name=user123&age=18”
{“age”:“18”,“name”:“user123”,“status”:{“status”:“ok”,“status_code”:200}}
File upload use
Use post Method , Type used multipart/form-data
Code
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
// initialization router
router := gin.Default()
// Definition POST Method path
router.POST("/upload", func(context *gin.Context) {
// Get the value passed
name := context.PostForm("name") // according to name Property to get the alias
file, err := context.FormFile("upload")
if err != nil {
context.JSON(http.StatusBadRequest, gin.H{
"status": gin.H{
"status_code": http.StatusBadRequest, "msg": "a bad request"}})
return
}
filename := file.Filename
if err := context.SaveUploadedFile(file, filename); err != nil {
context.JSON(http.StatusBadRequest, gin.H{
"status": gin.H{
"status_code": http.StatusBadRequest, "msg": "upload file err:" + err.Error()}})
return
}
// With JSON Format return
context.JSON(http.StatusOK, gin.H{
"status": gin.H{
"status_code": http.StatusOK, "status": "ok"}, "name":name,"filename": filename})
})
router.Run()
}
Access and return results

Multi route access
http://localhost:8080/v1/submit
http://localhost:8080/v1/login
http://localhost:8080/v1/read
http://localhost:8080/v2/submit
http://localhost:8080/v2/login
http://localhost:8080/v2/read
v1 := router.Group(“v1”)
{
v1.Get(“/login”, Method name )
}
Code
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func login(ctx *gin.Context) {
fmt.Println("this is a login method")
}
func main() {
// initialization router
router := gin.Default()
v1 := router.Group("v1")
{
v1.GET("/login", login)
}
v2 := router.Group("v2")
{
v2.GET("/login", login)
}
router.Run()
}
visit
http://127.0.0.1:8080/v1/login
http://127.0.0.1:8080/v2/login
版权声明
本文为[Liu Yuanshan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231751425184.html
边栏推荐
- 1217_ Generating target files using scons
- Uniapp custom search box adaptation applet alignment capsule
- Tdan over half
- Submit local warehouse and synchronize code cloud warehouse
- Utilisation de la liste - Ajouter, supprimer et modifier la requête
- Summary of common SQL statements
- 列表的使用-增删改查
- JS parsing and execution process
- 油猴网站地址
- This point in JS
猜你喜欢

SystemVerilog (VI) - variable

92. 反转链表 II-字节跳动高频题

高德地图搜索、拖拽 查询地址

Chrome浏览器的跨域设置----包含新老版本两种设置

394. String decoding - auxiliary stack

2022年流动式起重机司机国家题库模拟考试平台操作

Compilation principle first set follow set select set prediction analysis table to judge whether the symbol string conforms to the grammar definition (with source code!!!)

SystemVerilog(六)-变量

JS parsing and execution process

01 - get to know the advantages of sketch sketch
随机推荐
干货 | 快速抽取缩略图是怎么练成的?
Tdan over half
双指针进阶--leetcode题目--盛最多水的容器
394. 字符串解码-辅助栈
2021长城杯WP
Future 用法详解
C1 notes [task training part 2]
Error in created hook: "referenceerror:" promise "undefined“
Ring back to origin problem - byte jumping high frequency problem
Gets the time range of the current week
41. 缺失的第一个正数
Comparison between xtask and kotlin coroutine
Examination question bank and online simulation examination of the third batch (main person in charge) of special operation certificate of safety officer a certificate in Guangdong Province in 2022
Write a regular
2022制冷与空调设备运行操作判断题及答案
48. Rotate image
Allowed latency and side output
2022年上海市安全员C证操作证考试题库及模拟考试
Leak detection and vacancy filling (VII)
Commonly used functions -- spineros:: and spineros::)