gin.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * @Author: LinkLeong link@icewhale.com
  3. * @Date: 2021-10-08 10:29:08
  4. * @LastEditors: LinkLeong
  5. * @LastEditTime: 2022-07-22 11:06:07
  6. * @FilePath: /CasaOS/middleware/gin.go
  7. * @Description:
  8. * @Website: https://www.casaos.io
  9. * Copyright (c) 2022 by icewhale, All Rights Reserved.
  10. */
  11. package middleware
  12. import (
  13. "fmt"
  14. "net/http"
  15. "runtime/debug"
  16. "strings"
  17. "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
  18. "github.com/gin-gonic/gin"
  19. "go.uber.org/zap"
  20. )
  21. func Cors() gin.HandlerFunc {
  22. return func(c *gin.Context) {
  23. method := c.Request.Method
  24. c.Header("Access-Control-Allow-Origin", "*")
  25. c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
  26. // 允许跨域设置可以返回其他子段,可以自定义字段
  27. c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,Language,Content-Type,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Access-Control-Allow-Methods,Connection,Host,Origin,Referer,User-Agent,X-Requested-With")
  28. // 允许浏览器(客户端)可以解析的头部 (重要)
  29. c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
  30. // c.Writer.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, Content-Length, X-CSRF-Token, Token, session, Origin, Host, Connection, Accept-Encoding, Accept-Language, X-Requested-With")
  31. // 设置缓存时间
  32. c.Header("Access-Control-Max-Age", "172800")
  33. c.Header("Access-Control-Allow-Credentials", "true")
  34. c.Set("Content-Type", "application/json")
  35. //}
  36. // 允许类型校验
  37. if method == "OPTIONS" {
  38. c.JSON(http.StatusOK, "ok!")
  39. }
  40. defer func() {
  41. if err := recover(); err != nil {
  42. fmt.Println(err)
  43. debug.PrintStack()
  44. }
  45. }()
  46. c.Next()
  47. }
  48. }
  49. func WriteLog() gin.HandlerFunc {
  50. return func(c *gin.Context) {
  51. if !strings.Contains(c.Request.URL.String(), "password") {
  52. loger.Info("request:", zap.Any("path", c.Request.URL.String()), zap.Any("param", c.Params), zap.Any("query", c.Request.URL.Query()), zap.Any("method", c.Request.Method))
  53. c.Next()
  54. }
  55. }
  56. }