12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- // Copyright 2020 Lingfei Kong <colin404@foxmail.com>. All rights reserved.
- // Use of this source code is governed by a MIT style
- // license that can be found in the LICENSE file.
- package middleware
- import (
- "net/http"
- "time"
- "github.com/gin-gonic/gin"
- gindump "github.com/tpkeeper/gin-dump"
- )
- // Middlewares store registered middlewares.
- var Middlewares = defaultMiddlewares()
- // NoCache is a jwtauth function that appends headers
- // to prevent the client from caching the HTTP response.
- func NoCache(c *gin.Context) {
- c.Header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate, value")
- c.Header("Expires", "Thu, 01 Jan 1970 00:00:00 GMT")
- c.Header("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
- c.Next()
- }
- // Options is a jwtauth function that appends headers
- // for options requests and aborts then exits the jwtauth
- // chain and ends the request.
- func Options(c *gin.Context) {
- if c.Request.Method != "OPTIONS" {
- c.Next()
- } else {
- c.Header("Access-Control-Allow-Origin", "*")
- c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS")
- c.Header("Access-Control-Allow-Headers", "authorization, origin, content-type, accept")
- c.Header("Allow", "HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS")
- c.Header("Content-Type", "application/json")
- c.AbortWithStatus(http.StatusOK)
- }
- }
- // Secure is a jwtauth function that appends security
- // and resource access headers.
- func Secure(c *gin.Context) {
- c.Header("Access-Control-Allow-Origin", "*")
- c.Header("X-Frame-Options", "DENY")
- c.Header("X-Content-Type-Options", "nosniff")
- c.Header("X-XSS-Protection", "1; mode=block")
- if c.Request.TLS != nil {
- c.Header("Strict-Transport-Security", "max-age=31536000")
- }
- }
- func defaultMiddlewares() map[string]gin.HandlerFunc {
- return map[string]gin.HandlerFunc{
- "recovery": gin.Recovery(),
- "secure": Secure,
- "options": Options,
- "nocache": NoCache,
- "cors": Cors(),
- "requestid": RequestID(),
- "dump": gindump.Dump(),
- "logger": Logger(),
- }
- }
|