moonstream/moonstreamdb/server/cmd/middlewares.go

53 wiersze
1.5 KiB
Go
Czysty Zwykły widok Historia

2021-11-02 15:22:59 +00:00
package cmd
import (
"log"
2021-11-02 19:28:56 +00:00
"net/http"
"strings"
2021-11-02 15:22:59 +00:00
"time"
2021-11-02 19:28:56 +00:00
settings "github.com/bugout-dev/moonstream/db/server/configs"
2021-11-02 15:22:59 +00:00
)
// Handle panic errors to prevent server shutdown
func panicMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Println("recovered", err)
http.Error(w, "Internal server error", 500)
}
}()
// There will be a defer with panic handler in each next function
next.ServeHTTP(w, r)
})
}
// Log requests in proper format
func logsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
log.Printf("%s %s %s %s\n", time.Since(start), r.Method, r.URL.Path, r.RemoteAddr)
2021-11-02 15:22:59 +00:00
})
}
// CORS middleware
func corsMiddleware(next http.Handler) http.Handler {
// Iterate over list of allowed origins
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2021-11-02 19:28:56 +00:00
for _, allowedOrigin := range strings.Split(settings.MOONSTREAM_CORS_ALLOWED_ORIGINS, ",") {
if r.Header.Get("Origin") == allowedOrigin {
2021-11-02 19:28:56 +00:00
w.Header().Set("Access-Control-Allow-Origin", allowedOrigin)
2021-11-02 15:22:59 +00:00
}
}
if r.Method == "OPTIONS" {
w.Header().Set("Access-Control-Allow-Methods", "GET,OPTIONS")
// Credentials are cookies, authorization headers, or TLS client certificates
w.Header().Set("Access-Control-Allow-Credentials", "true")
2021-11-03 11:18:49 +00:00
w.Header().Set("Access-Control-Allow-Headers", "Authorization")
2021-11-02 15:22:59 +00:00
}
next.ServeHTTP(w, r)
})
}