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

2020-01-28 14:15:45刘景俊


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 地址: https://github.com/gin-gonic/gin
代码示例: https://github.com/hpifu/tpl-go-http

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。