123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- package server
- import (
- "fmt"
- "strings"
- "github.com/gin-gonic/gin"
- "kpt.notice/apiserver/config"
- "kpt.notice/apiserver/model/http"
- "kpt.notice/apiserver/service"
- "kpt.notice/pkg/log"
- )
- var (
- svc *service.Service
- )
- /*
- router init
- */
- func Init(s *service.Service, conf *config.Config) {
- svc = s
- engine := gin.New()
- engine.Use(gin.Recovery())
- engine.Use(Cors())
- route(engine)
- if err := engine.Run(conf.Listen); err != nil {
- panic(err)
- }
- }
- /*
- 跨域
- */
- func Cors() gin.HandlerFunc {
- return func(c *gin.Context) {
- method := c.Request.Method //请求方法
- origin := c.Request.Header.Get("Origin") //请求头部
- var headerKeys []string // 声明请求头keys
- for k := range c.Request.Header {
- headerKeys = append(headerKeys, k)
- }
- headerStr := strings.Join(headerKeys, ", ")
- if headerStr != "" {
- headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
- } else {
- headerStr = "access-control-allow-origin, access-control-allow-headers"
- }
- if origin != "" {
- c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
- c.Header("Access-Control-Allow-Origin", "*") // 这是允许访问所有域
- c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE") //服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
- // header的类型
- c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, id, Token, name, optname, thumbnail, session, X_Requested_With, Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
- // 允许跨域设置 可以返回其他子段
- c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma, FooBar") // 跨域关键设置 让浏览器可以解析
- c.Header("Access-Control-Max-Age", "172800") // 缓存请求信息 单位为秒
- c.Header("Access-Control-Allow-Credentials", "false") // 跨域请求是否需要带cookie信息 默认设置为true
- c.Set("content-type", "application/json") // 设置返回格式是json
- }
- //放行所有OPTIONS方法
- if method == "OPTIONS" {
- c.JSON(200, "Options Request!")
- }
- // 处理请求
- c.Next() // 处理请求
- }
- }
- /*
- router function list
- */
- func route(e *gin.Engine) {
- e.GET("/wx", tokenAuth) //wx office server address auth
- // receive wx message ,include common message and event message
- e.POST("/wx", wxMessage)
- // create temporary wx code for bind wx account
- e.GET("/wx/code", getCode)
- //receive business message
- e.POST("/notice/message", postMessage)
- // query notice type
- e.GET("/notice/msgtype", getMsgType)
- // save notice type
- e.POST("/notice/msgtype", postMsgType)
- }
- /*
- http 响应
- */
- func eJSON(c *gin.Context, data interface{}, err error) {
- code := 200
- success := true
- message := "ok"
- if err != nil {
- code, success, message = 400, false, err.Error()
- }
- resp := http.Response{
- Code: code,
- Success: success,
- Data: data,
- Message: message,
- }
- c.JSON(code, &resp)
- }
- /*
- requet validate
- */
- func Bind(c *gin.Context, req http.Request) bool {
- if err := c.ShouldBind(req); err != nil {
- eJSON(c, "request bind fail===", err)
- return false
- }
- log.Infof("body: %v", req)
- if err := req.Validate(); err != nil {
- log.Errorf("request validate fail: %v", err)
- eJSON(c, "request validate fail", req.Validate())
- return false
- }
- return true
- }
|