header.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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-Credentials", "true")
  23. c.Header("Access-Control-Allow-Origin", "*")
  24. c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS")
  25. c.Header("Access-Control-Allow-Headers", "authorization, origin, content-type, accept, X-Token, serviceId")
  26. c.Header("Allow", "HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS")
  27. c.Header("Content-Type", "application/json")
  28. c.AbortWithStatus(200)
  29. }
  30. }
  31. // Secure is a middleware function that appends security
  32. // and resource access headers.
  33. func Secure(c *gin.Context) {
  34. c.Header("Access-Control-Allow-Origin", "*")
  35. //c.Header("X-Frame-Options", "DENY")
  36. c.Header("X-Content-Type-Options", "nosniff")
  37. c.Header("X-XSS-Protection", "1; mode=block")
  38. if c.Request.TLS != nil {
  39. c.Header("Strict-Transport-Security", "max-age=31536000")
  40. }
  41. // Also consider adding Content-Security-Policy headers
  42. // c.Header("Content-Security-Policy", "script-src 'self' https://cdnjs.cloudflare.com")
  43. }