0
点赞
收藏
分享

微信扫一扫

GO语言gin框架初步介绍

guanguans 2022-01-08 阅读 62

1.下载gin框架

go get -u github.com/gin-gonic/gin

当无法下载时,大概率是被墙了
需要配置环境变量

go env -w GOPROXY=https://goproxy.io,direct
go env -w GOPRIVATE=*.corp.example.com

不建议使用

GO111MODULE=on 

因为创建其他项目的时候不能自动导入已下好的库
2.创造路由

r := gin.Default() //默认中间件的路由
r := gin.new()      //没有中间件的路由
r.GET("/user/:name",) 
c.Param("name")//可通过获取名称

3.发送请求,主要是get和post请求

r.GET("/cc", func(c*gin.Context))

c.Query(key) //get请求的参数
c.DefaultQuery(key1,key2 )//get请求的参数,没有则返回默认值

4.以json返回客户端

c.JSONP(http.StatusOK, data) //输出json格式
c.PureJSON(200, gin.H{
			"html": "<b>Hello, world!</b>",
		}//提供字面转换 不会转义
c.SecureJSON(http.StatusOK, names)//防止json被劫持

5.控制台以日志log的方式记录

f, _ := os.Create("gin.log")
gin.DefaultWriter = io.MultiWriter(f)

6.http一些设置 端口号等

s := &http.Server{
		Addr:           ":8080",
		Handler:        router,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
s.ListenAndServe()
--------------------------
r.run()//这是官方提供的接口

7.加载文件及文件夹

router.Static("/assets", "./assets")
router.StaticFS("/more_static", http.Dir("my_file_system"))
router.StaticFile("/favicon.ico", "./resources/favicon.ico")

8.重定向

c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")//重定向 这个前端也可以做

9.加载html页面

r.LoadHTMLGlob("./resources/html/*")#加载html
c.HTML(http.StatusOK,"test.html",nil)

这只是gin的部分用法,更多用法比如cookie session token headers等用法在github上有更多介绍
gin官方网址:https://github.com/gin-gonic

举报

相关推荐

0 条评论