header.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package middleware
  2. import (
  3. "net/http"
  4. "time"
  5. "github.com/gin-gonic/gin"
  6. )
  7. // NoCache is a middleware function that appends headers
  8. // to prevent the client from caching the HTTP response.
  9. func NoCache(c *gin.Context) {
  10. c.Header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate, value")
  11. c.Header("Expires", "Thu, 01 Jan 1970 00:00:00 GMT")
  12. c.Header("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
  13. c.Next()
  14. }
  15. // Options is a middleware function that appends headers
  16. // for options requests and aborts then exits the middleware
  17. // chain and ends the request.
  18. func Options(c *gin.Context) {
  19. if c.Request.Method != "OPTIONS" {
  20. c.Next()
  21. } else {
  22. c.Header("Access-Control-Allow-Origin", "*")
  23. c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS")
  24. c.Header("Access-Control-Allow-Headers", "authorization, origin, content-type, accept, X-Token, serviceId")
  25. c.Header("Allow", "HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS")
  26. c.Header("Content-Type", "application/json")
  27. c.AbortWithStatus(200)
  28. }
  29. }
  30. // Secure is a middleware function that appends security
  31. // and resource access headers.
  32. func Secure(c *gin.Context) {
  33. c.Header("Access-Control-Allow-Origin", "*")
  34. //c.Header("X-Frame-Options", "DENY")
  35. c.Header("X-Content-Type-Options", "nosniff")
  36. c.Header("X-XSS-Protection", "1; mode=block")
  37. if c.Request.TLS != nil {
  38. c.Header("Strict-Transport-Security", "max-age=31536000")
  39. }
  40. // Also consider adding Content-Security-Policy headers
  41. // c.Header("Content-Security-Policy", "script-src 'self' https://cdnjs.cloudflare.com")
  42. }