mw_cors.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package middleware
  2. import (
  3. "backend-linksee-api/common"
  4. "backend-linksee-api/utils"
  5. "github.com/gin-contrib/cors"
  6. "github.com/gin-gonic/gin"
  7. "strings"
  8. "time"
  9. )
  10. // CORSMiddleware 跨域请求中间件
  11. func CORSMiddleware() gin.HandlerFunc {
  12. return cors.New(cors.Config{
  13. AllowOrigins: []string{"*"},
  14. AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"},
  15. AllowHeaders: []string{"Origin, x-requested-with, Content-Type, X-Token,Authorization"},
  16. AllowCredentials: true,
  17. MaxAge: time.Second * time.Duration(7200),
  18. })
  19. }
  20. //func RecoredReq()gin.HandlerFunc {
  21. // return func(c *gin.Context) {
  22. // var postArgs = ""
  23. // var method = ""
  24. // if c.Request.Method == "post" {
  25. // data, _ := ioutil.ReadAll(c.Request.Body)
  26. // postArgs = string(data)
  27. // method = "post"
  28. // }else{
  29. // method = "get"
  30. // }
  31. // sql := `insert into btk_request_log(request,method,args)values(?,?,?)`
  32. // db, err := utils.OpenConnection()
  33. // if err != nil {
  34. // utils.LZPrint("RecoredReqErr",err.Error())
  35. // }
  36. // defer db.Close()
  37. // db.Exec(sql,c.getp)
  38. // }
  39. //}
  40. func ValidToken() gin.HandlerFunc {
  41. return func(c *gin.Context) {
  42. path := c.Request.URL.Path
  43. if strings.Index(path, "/order/pay/notify") == 0 || strings.Index(path, "login") != -1 || strings.Index(path, "swagger") != -1 || strings.Index(path, "panic") != -1 {
  44. //fmt.Println("path is:",path,strings.Index(path, "/order/pay/notify"))
  45. c.Next()
  46. } else {
  47. //fmt.Println("auth")
  48. tokens := strings.Replace(c.GetHeader("authorization"), "Bearer ", "", -1)
  49. if tokens == "" {
  50. common.ReturnFailure(c, 409, "token不能空", nil)
  51. c.Abort()
  52. return
  53. }
  54. _, err8 := utils.ParseToken(tokens)
  55. if err8 != nil {
  56. common.ReturnFailure(c, 409, err8.Error(), nil)
  57. c.Abort()
  58. }
  59. }
  60. }
  61. }