server.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. package server
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/gin-gonic/gin"
  6. "kpt.notice/apiserver/config"
  7. "kpt.notice/apiserver/model/http"
  8. "kpt.notice/apiserver/service"
  9. "kpt.notice/pkg/log"
  10. )
  11. var (
  12. svc *service.Service
  13. )
  14. /*
  15. router init
  16. */
  17. func Init(s *service.Service, conf *config.Config) {
  18. svc = s
  19. engine := gin.New()
  20. engine.Use(gin.Recovery())
  21. engine.Use(Cors())
  22. route(engine)
  23. if err := engine.Run(conf.Listen); err != nil {
  24. panic(err)
  25. }
  26. }
  27. /*
  28. 跨域
  29. */
  30. func Cors() gin.HandlerFunc {
  31. return func(c *gin.Context) {
  32. method := c.Request.Method //请求方法
  33. origin := c.Request.Header.Get("Origin") //请求头部
  34. var headerKeys []string // 声明请求头keys
  35. for k := range c.Request.Header {
  36. headerKeys = append(headerKeys, k)
  37. }
  38. headerStr := strings.Join(headerKeys, ", ")
  39. if headerStr != "" {
  40. headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
  41. } else {
  42. headerStr = "access-control-allow-origin, access-control-allow-headers"
  43. }
  44. if origin != "" {
  45. c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
  46. c.Header("Access-Control-Allow-Origin", "*") // 这是允许访问所有域
  47. c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE") //服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
  48. // header的类型
  49. 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")
  50. // 允许跨域设置 可以返回其他子段
  51. 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") // 跨域关键设置 让浏览器可以解析
  52. c.Header("Access-Control-Max-Age", "172800") // 缓存请求信息 单位为秒
  53. c.Header("Access-Control-Allow-Credentials", "false") // 跨域请求是否需要带cookie信息 默认设置为true
  54. c.Set("content-type", "application/json") // 设置返回格式是json
  55. }
  56. //放行所有OPTIONS方法
  57. if method == "OPTIONS" {
  58. c.JSON(200, "Options Request!")
  59. }
  60. // 处理请求
  61. c.Next() // 处理请求
  62. }
  63. }
  64. /*
  65. router function list
  66. */
  67. func route(e *gin.Engine) {
  68. e.GET("/wx", tokenAuth) //wx office server address auth
  69. // receive wx message ,include common message and event message
  70. e.POST("/wx", wxMessage)
  71. // create temporary wx code for bind wx account
  72. e.GET("/wx/code", getCode)
  73. //receive business message
  74. e.POST("/notice/message", postMessage)
  75. // query notice type
  76. e.GET("/notice/msgtype", getMsgType)
  77. // save notice type
  78. e.POST("/notice/msgtype", postMsgType)
  79. }
  80. /*
  81. http 响应
  82. */
  83. func eJSON(c *gin.Context, data interface{}, err error) {
  84. code := 200
  85. success := true
  86. message := "ok"
  87. if err != nil {
  88. code, success, message = 400, false, err.Error()
  89. }
  90. resp := http.Response{
  91. Code: code,
  92. Success: success,
  93. Data: data,
  94. Message: message,
  95. }
  96. c.JSON(code, &resp)
  97. }
  98. /*
  99. requet validate
  100. */
  101. func Bind(c *gin.Context, req http.Request) bool {
  102. if err := c.ShouldBind(req); err != nil {
  103. eJSON(c, "request bind fail===", err)
  104. return false
  105. }
  106. log.Infof("body: %v", req)
  107. if err := req.Validate(); err != nil {
  108. log.Errorf("request validate fail: %v", err)
  109. eJSON(c, "request validate fail", req.Validate())
  110. return false
  111. }
  112. return true
  113. }