upda/server/api_middleware.go
Varakh 1fc3818d3c
All checks were successful
/ build (push) Successful in 5m3s
feature(api,release): prepare for next major release and switch to requiring content-type set to JSON for all incoming requests and expose more CORS environment variables
- Switched to enforce JSON as Content-Type for all incoming requests
- Switched to properly respond with JSON on page not found or method not allowed
- Renamed CORS_ALLOW_ORIGIN to CORS_ALLOW_ORIGINS
- Added CORS_ALLOW_CREDENTIALS which defaults to true
- Added CORS_EXPOSE_HEADERS which defaults to *
- Overhauled package visibility for server module
2024-06-10 20:03:25 +02:00

80 lines
2.2 KiB
Go

package server
import (
"fmt"
"git.myservermanager.com/varakh/upda/api"
"github.com/gin-gonic/gin"
"net/http"
"strings"
)
func middlewareAppName() gin.HandlerFunc {
return func(c *gin.Context) {
c.Header(headerAppName, name)
c.Next()
}
}
func middlewareGlobalNotFound() gin.HandlerFunc {
return func(c *gin.Context) {
c.AbortWithStatusJSON(http.StatusNotFound, api.NewErrorResponseWithStatusAndMessage(string(notFound), "page not found"))
return
}
}
func middlewareGlobalMethodNotAllowed() gin.HandlerFunc {
return func(c *gin.Context) {
c.AbortWithStatusJSON(http.StatusMethodNotAllowed, api.NewErrorResponseWithStatusAndMessage(string(methodNotAllowed), "method not allowed"))
return
}
}
func middlewareEnforceJsonContentType() gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request.Method != http.MethodOptions && !strings.HasPrefix(c.GetHeader(headerContentType), headerContentTypeApplicationJson) {
c.AbortWithStatusJSON(http.StatusBadRequest, api.NewErrorResponseWithStatusAndMessage(string(illegalArgument), "content-type must be application/json"))
return
}
c.Next()
}
}
func middlewareAppVersion() gin.HandlerFunc {
return func(c *gin.Context) {
c.Header(headerAppVersion, version)
c.Next()
}
}
func middlewareAppContentType() gin.HandlerFunc {
return func(c *gin.Context) {
c.Header(headerContentType, headerContentTypeApplicationJson)
c.Next()
}
}
// middlewareErrorHandler handles global error handling, does not overwrite any given status (see -1)
func middlewareErrorHandler() gin.HandlerFunc {
return func(c *gin.Context) {
// call next first, so this is the last in chain
c.Next()
if len(c.Errors) > 0 {
// status -1 doesn't overwrite existing status code
c.Header(headerContentType, headerContentTypeApplicationJson)
c.JSON(-1, api.NewErrorResponseWithStatusAndMessage(errCodeToStr(c.Errors.Last()), c.Errors.Last().Error()))
return
}
}
}
func middlewareAppErrorRecoveryHandler() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, api.NewErrorResponseWithStatusAndMessage(string(general), fmt.Sprintf("%s", err)))
}
}()
c.Next()
}
}