pgweb/pkg/api/middleware.go
Dan Sosedoff 7a6450091a
Code formatting and cleanup (#442)
* Formatting, extract error messages
* More refactor
* Move errors to a separate file
* Add missing file
* Misc
2019-09-29 12:16:42 -05:00

68 lines
1.4 KiB
Go

package api
import (
"log"
"strings"
"github.com/gin-gonic/gin"
"github.com/sosedoff/pgweb/pkg/command"
)
// Middleware to check database connection status before running queries
func dbCheckMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
path := strings.Replace(c.Request.URL.Path, command.Opts.Prefix, "", -1)
// Allow whitelisted paths
if allowedPaths[path] {
c.Next()
return
}
// Check if session exists in single-session mode
if !command.Opts.Sessions {
if DbClient == nil {
badRequest(c, errNotConnected)
return
}
c.Next()
return
}
// Determine session ID from the client request
sid := getSessionId(c.Request)
if sid == "" {
badRequest(c, errSessionRequired)
return
}
// Determine the database connection handle for the session
conn := DbSessions[sid]
if conn == nil {
badRequest(c, errNotConnected)
return
}
c.Next()
}
}
// Middleware to print out request parameters and body for debugging
func requestInspectMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
err := c.Request.ParseForm()
log.Println("Request params:", err, c.Request.Form)
}
}
// Middleware to inject CORS headers
func corsMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
c.Header("Access-Control-Expose-Headers", "*")
c.Header("Access-Control-Allow-Origin", command.Opts.CorsOrigin)
}
}