当前位置:网站首页>Go的Gin框架学习
Go的Gin框架学习
2022-04-23 17:51:00 【刘远山】
框架安装
1、设置代理
在下载gin框架之前,我们还需要配置go公共代理镜像,目的是解决github无法访问或者访问速度慢的问题,在cmd窗口中执行命令:
# 这里我设置成自动模式,on的模式我开启后莫名的无法执行gin代码下载
go env -w GO111MODULE=auto
# 设置代理
go env -w GOPROXY=https://goproxy.io,direct
2、下载gin框架
go get -u github.com/gin-gonic/gin
3、创建demo项目,运行gin框架
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、缺少包报错问题处理
由于网络原因,此处与google相关的包无法访问,需要单独下载
..\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)在GOPATH目录的src目录下,新建文件夹google.golang.org,然后cmd窗口中,切换到该目录下,执行命令:
注意不是github.com目录下,而是src目录下
D:\go_work\src\google.golang.org
git clone https://github.com/protocolbuffers/protobuf-go.git
下载完成后,将protobuf-go目录重命名为protobuf

2)由于网络原因,此处与golang.org相关的包也无法下载
在GOPATH目录的src目录下,新建文件夹golang.org,然后cmd窗口中,切换到该目录下,执行命令:
注意不是github.com目录下,而是src目录下
D:\go_work\src\golang.org
git clone https://github.com/golang/tools.git
下载完成后,将tools目录重命名为x

3)进入x目录,继续执行命令:
D:\go_work\src\golang.org\x
git clone https://github.com/golang/crypto.git
4)根据需要安装github.com缺失的包
1、进入D:\go_work\src\github.com\go-playground目录下
git clone https://github.com/go-playground/locales.git
2、进入D:\go_work\src\github.com\leodido目录下
git clone https://github.com/leodido/go-urn.git
3、进入D:\go_work\src\github.com\mattn目录下
git clone https://github.com/mattn/go-isatty.git
4、进入D:\go_work\src\github.com\ugorji目录下
报错提示:cannot find package “github.com/ugorji/go/codec” in any of:
git clone https://github.com/ugorji/go.git
5、进入D:\go_work\src\golang.org\x目录下,缺少net包
报错提示: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、进入D:\go_work\src\golang.org\x目录下,缺少text包
报错提示: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
成功开启服务
访问:http://127.0.0.1:3333/


简单路由的使用
gin的路由来自与httprouter库,因此httprouter具有的功能gin也具有
实战
代码:
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
//初始化router
router := gin.Default()
//定义路径,使用冒号:代替变量
router.GET("/user/:name/:age", func(context *gin.Context) {
//获取name值
name := context.Param("name")
age := context.Param("age")
message := name + " is " + age
//返回值
context.String(http.StatusOK, "hello %s", message)
})
router.Run()
}
访问
http://127.0.0.1:8080/user/user11/18
Get请求使用
1、context.DefaultQuery 取不到值时设置默认值
2、context.Query 直接取值
代码
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
//初始化router
router := gin.Default()
//定义路径
router.GET("/user/", func(context *gin.Context) {
//获取name值
name := context.DefaultQuery("name","默认值")
age := context.Query("age")
message := name + " is " + age
//返回值
context.String(http.StatusOK, "hello %s", message)
})
router.Run()
}
访问
http://127.0.0.1:8080/user/?name=user1&age=18
Post请求使用
常见场景
1、application/json (request中发送json数据,用post方式发送Content-type用application/json)
2、application/x-www-form-urlencode (常见的表单提交,把query_string的内容放到body体内,同样需要urlencode)
3、application/xml (http作为传输协议,xml作为编码方式远程调用规范)
4、multipart/form-data(文件传输)
代码
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
//初始化router
router := gin.Default()
//定义POST方法路径
router.POST("/form_post", func(context *gin.Context) {
//获取传递的值
name := context.PostForm("name")
age := context.DefaultPostForm("age","10")
//以JSON格式返回
context.JSON(http.StatusOK, gin.H{
"status":gin.H{
"status_code":http.StatusOK,"status":"ok"},"name":name,"age":age})
})
router.Run()
}
访问与返回结果
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}}
文件上传使用
使用post方法,类型使用multipart/form-data
代码
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
//初始化router
router := gin.Default()
//定义POST方法路径
router.POST("/upload", func(context *gin.Context) {
//获取传递的值
name := context.PostForm("name") //根据name属性获取别名
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
}
//以JSON格式返回
context.JSON(http.StatusOK, gin.H{
"status": gin.H{
"status_code": http.StatusOK, "status": "ok"}, "name":name,"filename": filename})
})
router.Run()
}
访问与返回结果

多路由访问
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”,方法名)
}
代码
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func login(ctx *gin.Context) {
fmt.Println("this is a login method")
}
func main() {
//初始化router
router := gin.Default()
v1 := router.Group("v1")
{
v1.GET("/login", login)
}
v2 := router.Group("v2")
{
v2.GET("/login", login)
}
router.Run()
}
访问
http://127.0.0.1:8080/v1/login
http://127.0.0.1:8080/v2/login
版权声明
本文为[刘远山]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_39218464/article/details/124318134
边栏推荐
- C1 notes [task training chapter I]
- Commonly used functions -- spineros:: and spineros::)
- JS high frequency interview questions
- 列錶的使用-增删改查
- Halo open source project learning (II): entity classes and data tables
- 386. 字典序排数(中等)-迭代-全排列
- MySQL进阶学习之SQL优化【插入,主键,排序,分组,分页,计数】
- uni-app黑马优购项目学习记录(下)
- 2022制冷与空调设备运行操作判断题及答案
- JS get link? The following parameter name or value, according to the URL? Judge the parameters after
猜你喜欢

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 (VI) - variable

Qt error: /usr/bin/ld: cannot find -lGL: No such file or directory
![MySQL advanced index [classification, performance analysis, use, design principles]](/img/96/b031868602a7b8ba4edd0d74c843b3.png)
MySQL advanced index [classification, performance analysis, use, design principles]

Detailed deployment of flask project

EasymodbusTCP之clientexample解析

索引:手把手教你索引从零基础到精通使用

48. Rotate image

2022制冷与空调设备运行操作判断题及答案

2022 judgment questions and answers for operation of refrigeration and air conditioning equipment
随机推荐
2022 tea artist (primary) examination simulated 100 questions and simulated examination
Cross domain settings of Chrome browser -- including new and old versions
读《Software Engineering at Google》(15)
Type judgment in [untitled] JS
Halo 开源项目学习(二):实体类与数据表
索引:手把手教你索引从零基础到精通使用
Construction of functions in C language programming
Encapsulate a timestamp to date method on string prototype
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
Open source key component multi_ Button use, including test engineering
极致体验,揭晓抖音背后的音视频技术
Write a regular
Tdan over half
干货 | 快速抽取缩略图是怎么练成的?
198. 打家劫舍-动态规划
ros常用的函数——ros::ok(),ros::Rate,ros::spin()和ros::spinOnce()
470. 用 Rand7() 实现 Rand10()
Use of list - addition, deletion, modification and query
2022年广东省安全员A证第三批(主要负责人)特种作业证考试题库及在线模拟考试
JS parsing and execution process