Last active
April 6, 2020 22:49
-
-
Save victorsteven/d29d578c21bd88a161dd52bac9a3af0b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package middleware | |
import ( | |
"bytes" | |
"food-app/infrastructure/auth" | |
"github.com/gin-gonic/gin" | |
"io/ioutil" | |
"net/http" | |
) | |
func AuthMiddleware() gin.HandlerFunc { | |
return func(c *gin.Context) { | |
err := auth.TokenValid(c.Request) | |
if err != nil { | |
c.JSON(http.StatusUnauthorized, gin.H{ | |
"status": http.StatusUnauthorized, | |
"error": err.Error(), | |
}) | |
c.Abort() | |
return | |
} | |
c.Next() | |
} | |
} | |
func CORSMiddleware() gin.HandlerFunc { | |
return func(c *gin.Context) { | |
c.Writer.Header().Set("Access-Control-Allow-Origin", "*") | |
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") | |
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With") | |
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, PATCH, DELETE") | |
if c.Request.Method == "OPTIONS" { | |
c.AbortWithStatus(204) | |
return | |
} | |
c.Next() | |
} | |
} | |
//Avoid a large file from loading into memory | |
//If the file size is greater than 8MB dont allow it to even load into memory and waste our time. | |
func MaxSizeAllowed(n int64) gin.HandlerFunc { | |
return func(c *gin.Context) { | |
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, n) | |
buff, errRead := c.GetRawData() | |
if errRead != nil { | |
//c.JSON(http.StatusRequestEntityTooLarge,"too large") | |
c.JSON(http.StatusRequestEntityTooLarge, gin.H{ | |
"status": http.StatusRequestEntityTooLarge, | |
"upload_err": "too large: upload an image less than 8MB", | |
}) | |
c.Abort() | |
return | |
} | |
buf := bytes.NewBuffer(buff) | |
c.Request.Body = ioutil.NopCloser(buf) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment