栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

Go的Gin框架学习

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Go的Gin框架学习

框架安装

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.comgo-playgrounduniversal-translatorerrors.go:7:2: cannot find package "github.com/go-playground/locales" in any of:
	C:Program FilesGosrcgithub.comgo-playgroundlocales (from $GOROOT)
	D:go_worksrcgithub.comgo-playgroundlocales (from $GOPATH)
..github.comgo-playgroundvalidatorbaked_in.go:23:2: cannot find package "github.com/leodido/go-urn" in any of:
	C:Program FilesGosrcgithub.comleodidogo-urn (from $GOROOT)
	D:go_worksrcgithub.comleodidogo-urn (from $GOPATH)
..github.comgin-gonicginlogger.go:14:2: cannot find package "github.com/mattn/go-isatty" in any of:
	C:Program FilesGosrcgithub.commattngo-isatty (from $GOROOT)
	D:go_worksrcgithub.commattngo-isatty (from $GOPATH)
..github.comgin-gonicginbindingmsgpack.go:15:2: cannot find package "github.com/ugorji/go/codec" in any of:
	C:Program FilesGosrcgithub.comugorjigocodec (from $GOROOT)
	D:go_worksrcgithub.comugorjigocodec (from $GOPATH)
..github.comgo-playgroundvalidatorbaked_in.go:20:2: cannot find package "golang.org/x/crypto/sha3" in any of:
	C:Program FilesGosrcgolang.orgxcryptosha3 (from $GOROOT)
	D:go_worksrcgolang.orgxcryptosha3 (from $GOPATH)
..github.comgin-gonicgingin.go:19:2: cannot find package "golang.org/x/net/http2" in any of:
	C:Program FilesGosrcgolang.orgxnethttp2 (from $GOROOT)
	D:go_worksrcgolang.orgxnethttp2 (from $GOPATH)
..github.comgin-gonicgingin.go:20:2: cannot find package "golang.org/x/net/http2/h2c" in any of:
	C:Program FilesGosrcgolang.orgxnethttp2h2c (from $GOROOT)
	D:go_worksrcgolang.orgxnethttp2h2c (from $GOPATH)
..github.comgo-playgroundvalidatorbaked_in.go:21:2: cannot find package "golang.org/x/text/language" in any of:
	C:Program FilesGosrcgolang.orgxtextlanguage (from $GOROOT)
	D:go_worksrcgolang.orgxtextlanguage (from $GOPATH)
..github.comgin-gonicginbindingprotobuf.go:12:2: cannot find package "google.golang.org/protobuf/proto" in any of:
	C:Program FilesGosrcgoogle.golang.orgprotobufproto (from $GOROOT)
	D:go_worksrcgoogle.golang.orgprotobufproto (from $GOPATH)

Compilation finished with exit code 1

1)在GOPATH目录的src目录下,新建文件夹google.golang.org,然后cmd窗口中,切换到该目录下,执行命令:
注意不是github.com目录下,而是src目录下
D:go_worksrcgoogle.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_worksrcgolang.org

git clone https://github.com/golang/tools.git

下载完成后,将tools目录重命名为x

3)进入x目录,继续执行命令:
D:go_worksrcgolang.orgx

git clone https://github.com/golang/crypto.git

4)根据需要安装github.com缺失的包
1、进入D:go_worksrcgithub.comgo-playground目录下

git clone https://github.com/go-playground/locales.git

2、进入D:go_worksrcgithub.comleodido目录下

git clone https://github.com/leodido/go-urn.git

3、进入D:go_worksrcgithub.commattn目录下

git clone https://github.com/mattn/go-isatty.git

4、进入D:go_worksrcgithub.comugorji目录下
报错提示:cannot find package “github.com/ugorji/go/codec” in any of:

git clone https://github.com/ugorji/go.git

5、进入D:go_worksrcgolang.orgx目录下,缺少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_worksrcgolang.orgx目录下,缺少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_worksrc>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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/990741.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号