middleware.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2020 Lingfei Kong <colin404@foxmail.com>. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package middleware
  5. import (
  6. "net/http"
  7. "time"
  8. "github.com/gin-gonic/gin"
  9. gindump "github.com/tpkeeper/gin-dump"
  10. )
  11. // Middlewares store registered middlewares.
  12. var Middlewares = defaultMiddlewares()
  13. // NoCache is a middleware function that appends headers
  14. // to prevent the client from caching the HTTP response.
  15. func NoCache(c *gin.Context) {
  16. c.Header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate, value")
  17. c.Header("Expires", "Thu, 01 Jan 1970 00:00:00 GMT")
  18. c.Header("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
  19. c.Next()
  20. }
  21. // Options is a middleware function that appends headers
  22. // for options requests and aborts then exits the middleware
  23. // chain and ends the request.
  24. func Options(c *gin.Context) {
  25. if c.Request.Method != "OPTIONS" {
  26. c.Next()
  27. } else {
  28. c.Header("Access-Control-Allow-Origin", "*")
  29. c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS")
  30. c.Header("Access-Control-Allow-Headers", "authorization, origin, content-type, accept")
  31. c.Header("Allow", "HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS")
  32. c.Header("Content-Type", "application/json")
  33. c.AbortWithStatus(http.StatusOK)
  34. }
  35. }
  36. // Secure is a middleware function that appends security
  37. // and resource access headers.
  38. func Secure(c *gin.Context) {
  39. c.Header("Access-Control-Allow-Origin", "*")
  40. c.Header("X-Frame-Options", "DENY")
  41. c.Header("X-Content-Type-Options", "nosniff")
  42. c.Header("X-XSS-Protection", "1; mode=block")
  43. if c.Request.TLS != nil {
  44. c.Header("Strict-Transport-Security", "max-age=31536000")
  45. }
  46. }
  47. func defaultMiddlewares() map[string]gin.HandlerFunc {
  48. return map[string]gin.HandlerFunc{
  49. "recovery": gin.Recovery(),
  50. "secure": Secure,
  51. "options": Options,
  52. "nocache": NoCache,
  53. "cors": Cors(),
  54. "dump": gindump.Dump(),
  55. }
  56. }