当前位置:网站首页>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
边栏推荐
- Future 用法详解
- Utilisation de la liste - Ajouter, supprimer et modifier la requête
- 列錶的使用-增删改查
- 读《Software Engineering at Google》(15)
- [binary number] maximum depth of binary tree + maximum depth of n-ary tree
- 01 - get to know the advantages of sketch sketch
- 高德地图搜索、拖拽 查询地址
- 958. 二叉树的完全性检验
- Detailed deployment of flask project
- Cross domain settings of Chrome browser -- including new and old versions
猜你喜欢

440. The k-th small number of dictionary order (difficult) - dictionary tree - number node - byte skipping high-frequency question

Learning record of uni app dark horse yougou project (Part 2)

Allowed latency and side output

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!!!)

2021长城杯WP

土地覆盖/利用数据产品下载

2022 tea artist (primary) examination simulated 100 questions and simulated examination

Eigen learning summary

Qt error: /usr/bin/ld: cannot find -lGL: No such file or directory

C1小笔记【任务训练篇一】
随机推荐
Special effects case collection: mouse planet small tail
Halo 开源项目学习(二):实体类与数据表
开源按键组件Multi_Button的使用,含测试工程
Tdan over half
索引:手把手教你索引从零基础到精通使用
Cloud native Virtualization: building edge computing instances based on kubevirt
209. 长度最小的子数组-滑动窗口
Summary of floating point double precision, single precision and half precision knowledge
Arithmetic expression
MySQL进阶之索引【分类,性能分析,使用,设计原则】
Error in created hook: "referenceerror:" promise "undefined“
Chrome浏览器的跨域设置----包含新老版本两种设置
【Appium】通过设计关键字驱动文件来编写脚本
圆环回原点问题-字节跳动高频题
Type judgment in [untitled] JS
2022年广东省安全员A证第三批(主要负责人)特种作业证考试题库及在线模拟考试
Anchor location - how to set the distance between the anchor and the top of the page. The anchor is located and offset from the top
239. 滑动窗口最大值(困难)-单向队列、大顶堆-字节跳动高频题
198. 打家劫舍-动态规划
470. Rand10() is implemented with rand7()