gin.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. "strings"
  16. "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
  17. "github.com/gin-gonic/gin"
  18. "go.uber.org/zap"
  19. )
  20. func Cors() gin.HandlerFunc {
  21. return func(c *gin.Context) {
  22. method := c.Request.Method
  23. c.Header("Access-Control-Allow-Origin", "*")
  24. c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
  25. //允许跨域设置可以返回其他子段,可以自定义字段
  26. 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")
  27. // 允许浏览器(客户端)可以解析的头部 (重要)
  28. c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
  29. //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")
  30. //设置缓存时间
  31. c.Header("Access-Control-Max-Age", "172800")
  32. c.Header("Access-Control-Allow-Credentials", "true")
  33. c.Set("Content-Type", "application/json")
  34. //}
  35. //允许类型校验
  36. if method == "OPTIONS" {
  37. c.JSON(http.StatusOK, "ok!")
  38. }
  39. defer func() {
  40. if err := recover(); err != nil {
  41. fmt.Println(err)
  42. }
  43. }()
  44. c.Next()
  45. }
  46. }
  47. func WriteLog() gin.HandlerFunc {
  48. return func(c *gin.Context) {
  49. if !strings.Contains(c.Request.URL.String(), "password") {
  50. 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))
  51. c.Next()
  52. }
  53. }
  54. }