当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > golang 网络框架之gin的使用方法

golang 网络框架之gin的使用方法

2020年03月09日  | 移动技术网IT编程  | 我要评论

golang 原生 http 库已经可以很方便地实现一个 http server 了,但对于复杂的 web 服务来说,路由解析,请求参数解析,对象返回等等,原生 api 就显得有些不太够用了,而 gin 是一个功能完备,性能很高的 web 网络框架,特别适合 web api 的开发

hello world

package main

import "github.com/gin-gonic/gin"

func main() {
  r := gin.new()
  r.get("/ping", func(c *gin.context) {
    c.string(200, "hello world")
  })
  r.run() // listen and serve on 0.0.0.0:8080
}

如这个 hello world 程序所示 gin 所有的业务逻辑都在 func(c *gin.context) 函数中实现,请求和返回都通过这个 gin.context 传递

请求参数解析

gin 提供了丰富的请求参数获取方式

(c *context) query(key string) string        // 获取 get 参数
(c *context) queryarray(key string) []string    // 获取 get 参数数组
(c *context) defaultquery(key, defaultvalue string) // 获取 get 参数,并提供默认值
(c *context) param(key string) string        // 获取 param 参数,类似于 "/user/:id"
(c *context) getrawdata() ([]byte, error)      // 获取 body 数据

但这些函数我都不建议使用,建议用结构体来描述请求,再使用 bind api 直接将获取请求参数

type helloworldreq struct {
  token  string `json:"token"`
  id    int  `json:"id" uri:"id"`
  email  string `json:"email" form:"email"`
  password string `json:"password" form:"password"`
}

req := &helloworldreq{
  token: c.getheader("authorization"),  // 头部字段无法 bind,可以通过 getheader 获取
}

// 用请求中的 param 参数填充结构体中的 uri 字段
if err := c.binduri(req); err != nil {
  return nil, nil, http.statusbadrequest, fmt.errorf("bind uri failed. err: [%v]", err)
}

// get 请求中用 query 参数填充 form 字段
// 非 get 请求,将 body 中的 json 或者 xml 反序列化后填充 form 字段
if err := c.bind(req); err != nil {
  return nil, nil, http.statusbadrequest, fmt.errorf("bind failed. err: [%v]", err)
}

http 的客户端 ip 一般在请求头的 x-forwarded-for 和 x-real-ip 中,gin 提供了 (c *context) clientip() string 来获取 ip

返回包体

(c *context) string(code int, format string, values ...interface{}) // 返回一个字符串
(c *context) json(code int, obj interface{})            // 返回一个 json
(c *context) status(code int)                    // 返回一个状态码

文件上传和返回

从请求中获取文件

fh, err := ctx.formfile("file")
if err != nil {
  return err
}

src, err := fh.open()
if err != nil {
  return err
}
defer src.close()

返回文件

(c *context) file(filepath string)

cros 跨域

服务端返回的头部中有个字段 "access-control-allow-origin",如果该字段和请求的域不同,浏览器会被浏览器拒绝,其实这个地方我理解应该是客户端没有权限访问,服务端不该返回结果,浏览器认为结果不可用,所以提示跨域错误,而这个头部字段还只能写一个地址,或者写成 *,对所有网站都开放,要想对多个网站开发,我们可以根据请求的 "origin" 字段,动态地设置 "access-control-allow-origin" 字段,满足权限得设置成请求中的 "origin" 字段,gin 的有个插件 github.com/gin-contrib/cors 就是专门用来做这个事情的,可以在 alloworigins 中设置多个网站,还可以设置通配符(需设置 allowwildcard 为 true)

import "github.com/gin-contrib/cors"

r := gin.new()
r.use(cors.new(cors.config{
  alloworigins:   []string{"a.example.com", "b.example.com"},
  allowmethods:   []string{"put", "post", "get", "options"},
  allowheaders:   []string{"origin", "content-type", "content-length", "accept-encoding", "x-csrf-token", "authorization", "accept", "cache-control", "x-requested-with"},
  allowcredentials: true,
}))

cookies

// maxage 为过期时间
// domain 是网站的地址,如需跨域共享 cookie,可以设置成域名,
//   比如 a.example.com 和 b.example.com,可以将 domain 设置成 example.com
// secure 为 https 设为 true,http 设为 false
// httponly 设置为 false,否则 axios 之类的库访问不到 cookie
(c *context) setcookie(name, value string, maxage int, path, domain string, secure, httponly bool)

另外,axios 需要设置 withcredentials: true cookie 才能正常返回

链接

github 地址:
代码示例:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网