middleware.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package middleware
  2. import (
  3. "net/http"
  4. "time"
  5. "bet24.com/log"
  6. "github.com/gin-gonic/gin"
  7. "github.com/unrolled/secure"
  8. )
  9. // 身份验证(MD5)
  10. func CheckValid() gin.HandlerFunc {
  11. return func(c *gin.Context) {
  12. _ = c.Request.ParseForm()
  13. req := c.Request.Form
  14. path := c.Request.URL.Path
  15. rawPath := c.Request.URL.RawPath
  16. log.Debug("%s ==> %s", path, req)
  17. start := time.Now()
  18. c.Next()
  19. //记录耗时信息
  20. if latency := time.Now().Sub(start); latency > 10*time.Second {
  21. log.Release("%v %v 访问耗时 %v =====> %+v",
  22. path, rawPath, latency, req)
  23. }
  24. }
  25. }
  26. // 跨域中间件
  27. // 要在路由组之前全局使用「跨域中间件」, 否则OPTIONS会返回404
  28. func Cors() gin.HandlerFunc {
  29. return func(c *gin.Context) {
  30. method := c.Request.Method
  31. origin := c.Request.Header.Get("Origin")
  32. if origin != "" {
  33. c.Header("Access-Control-Allow-Origin", origin)
  34. c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
  35. c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
  36. c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
  37. c.Header("Access-Control-Allow-Credentials", "false")
  38. c.Set("content-type", "application/json")
  39. }
  40. if method == "OPTIONS" {
  41. c.AbortWithStatus(http.StatusNoContent)
  42. return
  43. }
  44. c.Next()
  45. }
  46. }
  47. func TlsHandler() gin.HandlerFunc {
  48. return func(c *gin.Context) {
  49. secureMiddleware := secure.New(secure.Options{
  50. SSLRedirect: true,
  51. SSLHost: ":443",
  52. })
  53. err := secureMiddleware.Process(c.Writer, c.Request)
  54. if err != nil {
  55. c.Abort()
  56. return
  57. }
  58. c.Next()
  59. }
  60. }