当前位置:网站首页>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
边栏推荐
- 1217_使用SCons生成目标文件
- [二叉数] 二叉树的最大深度+N叉树的最大深度
- Qt error: /usr/bin/ld: cannot find -lGL: No such file or directory
- Ring back to origin problem - byte jumping high frequency problem
- ES6 new method
- Where is the configuration file of tidb server?
- Cloud native Virtualization: building edge computing instances based on kubevirt
- 2022年茶艺师(初级)考试模拟100题及模拟考试
- 云原生虚拟化:基于 Kubevirt 构建边缘计算实例
- Leak detection and vacancy filling (VII)
猜你喜欢
On the method of outputting the complete name of typeID from GCC
Dry goods | how to extract thumbnails quickly?
Halo open source project learning (II): entity classes and data tables
2021 Great Wall Cup WP
Leak detection and vacancy filling (6)
Comparison between xtask and kotlin coroutine
云原生虚拟化:基于 Kubevirt 构建边缘计算实例
HCIP第五次实验
2022 judgment questions and answers for operation of refrigeration and air conditioning equipment
440. The k-th small number of dictionary order (difficult) - dictionary tree - number node - byte skipping high-frequency question
随机推荐
Write a regular
01 - get to know the advantages of sketch sketch
C1 notes [task training part 2]
双指针进阶--leetcode题目--盛最多水的容器
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!!!)
Welcome to the markdown editor
Leak detection and vacancy filling (6)
440. The k-th small number of dictionary order (difficult) - dictionary tree - number node - byte skipping high-frequency question
122. The best time to buy and sell stocks II - one-time traversal
2022 judgment questions and answers for operation of refrigeration and air conditioning equipment
Vite configure proxy proxy to solve cross domain
Commonly used functions -- spineros:: and spineros::)
402. Remove K digits - greedy
Add animation to the picture under V-for timing
JVM类加载机制
SQL optimization for advanced learning of MySQL [insert, primary key, sort, group, page, count]
Submit local warehouse and synchronize code cloud warehouse
Timestamp to formatted date
油猴网站地址
SystemVerilog(六)-变量