This repository has been archived on 2024-04-07. You can view files and clone it, but cannot push or open issues or pull requests.
summer-utils/api/api.go
2023-04-16 13:22:04 +01:00

94 lines
2.1 KiB
Go

package api
import (
"code.mrmelon54.com/melon/summer-utils/utils"
"code.mrmelon54.com/melon/summer-utils/utils/debug"
"encoding/json"
"errors"
"fmt"
"github.com/golang-jwt/jwt/v4"
"github.com/google/uuid"
"github.com/gorilla/mux"
"golang.org/x/crypto/bcrypt"
"log"
"net/http"
"runtime"
"time"
)
var (
ErrNoError = errors.New("no error")
ErrParamMissing = errors.New("parameter is missing")
ErrParamWrongType = errors.New("parameter is of the wrong type")
noLogErrors = []error{
ErrNoError,
ErrParamMissing,
ErrParamWrongType,
}
// prevent logging these to stop clutter of the logs
noLogProdErrors = []error{
bcrypt.ErrMismatchedHashAndPassword,
jwt.ErrTokenInvalidClaims,
jwt.ErrTokenMalformed,
jwt.ErrTokenExpired,
}
)
type logErrorOutput struct {
Message string `json:"message"`
LogId string `json:"log_id"`
}
func GenericErrorMsg[T any](rw http.ResponseWriter, err error, code int, msg string, args ...any) bool {
if err == nil {
return false
}
m := fmt.Sprintf(msg, args...)
u := fmt.Sprintf("LOG_%s", uuid.New())
var noLog bool
for _, i := range noLogErrors {
if errors.Is(err, i) {
noLog = true
}
}
if !debug.IsDebug() {
for _, i := range noLogProdErrors {
if errors.Is(err, i) {
noLog = true
}
}
}
if !noLog {
var pr string
_, file, line, ok := runtime.Caller(1)
if ok {
pr = fmt.Sprintf(" (%s:%d)", file, line)
}
log.Printf("[GenericApi::%T] {%s}%s %s: %s\n", *new(T), u, pr, m, err)
}
rw.Header().Set("Content-Type", "application/json")
rw.Header().Set("X-Content-Type-Options", "nosniff")
rw.WriteHeader(code)
_ = json.NewEncoder(rw).Encode(logErrorOutput{
Message: m,
LogId: u,
})
return true
}
func RunApiServer(listen string, router *mux.Router) *http.Server {
s := &http.Server{
Addr: listen,
Handler: router,
ReadTimeout: 1 * time.Minute,
ReadHeaderTimeout: 1 * time.Minute,
WriteTimeout: 1 * time.Minute,
IdleTimeout: 1 * time.Minute,
MaxHeaderBytes: 2500,
}
log.Printf("[API] Starting API server on: '%s'\n", s.Addr)
go utils.RunBackgroundHttp("API", s)
return s
}