mirror of
https://git.freecumextremist.com/grumbulon/pomme.git
synced 2024-11-05 10:54:10 +00:00
77 lines
1.8 KiB
Go
77 lines
1.8 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.freecumextremist.com/grumbulon/pomme/internal"
|
|
"git.freecumextremist.com/grumbulon/pomme/internal/db"
|
|
"github.com/go-chi/httplog"
|
|
"github.com/go-chi/render"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// setDBMiddleware is the http Handler func for the GORM middleware with context.
|
|
func setDBMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
var pommeDB *gorm.DB
|
|
c, err := internal.ReadConfig()
|
|
if err != nil {
|
|
log.Printf("No config file defined: %v", err)
|
|
}
|
|
|
|
switch r.Header.Get("User-Agent") {
|
|
case "pomme-api-test-slave":
|
|
pommeDB = db.InitDb(c.TestDB)
|
|
default:
|
|
pommeDB = db.InitDb(c.DB)
|
|
}
|
|
|
|
timeoutContext, cancelContext := context.WithTimeout(context.Background(), time.Second)
|
|
ctx := context.WithValue(r.Context(), keyPrincipalContextID, pommeDB.WithContext(timeoutContext))
|
|
defer cancelContext()
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
func APIError[T map[string]any](w http.ResponseWriter, r *http.Request, v map[string]any) {
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
|
|
logHandler(v)
|
|
|
|
switch v["realm"] {
|
|
default:
|
|
w.Header().Add("WWW-Authenticate", fmt.Sprintf(`realm="%s"`, v["realm"].(string)))
|
|
|
|
fallthrough
|
|
case nil:
|
|
w.Header().Add("API Error", v["message"].(string))
|
|
}
|
|
|
|
w.WriteHeader(v["status"].(int))
|
|
|
|
// remove unnecessary items from response
|
|
delete(v, "error")
|
|
delete(v, "status")
|
|
|
|
render.JSON(w, r, v)
|
|
}
|
|
|
|
func logHandler(v map[string]any) {
|
|
logger := httplog.NewLogger("Pomme", httplog.Options{
|
|
JSON: true,
|
|
})
|
|
|
|
switch v["error"] {
|
|
default:
|
|
logger.Error().Msg(v["error"].(string))
|
|
|
|
fallthrough
|
|
case nil:
|
|
logger.Info().Msg(v["message"].(string))
|
|
}
|
|
}
|