draincloud-core/internal/common/request.go

64 lines
1.2 KiB
Go

package common
import (
"fmt"
"net/http"
"sync"
"git.optclblast.xyz/draincloud/draincloud-core/internal/storage/models"
"github.com/google/uuid"
)
type RequestPool struct {
sp sync.Pool
}
type Request struct {
ID string
Session *models.Session
User *models.User
ResolveValues sync.Map
Metadata map[string]any
Body []byte
}
// NewRequest builds a new *Request struct from raw http Request. No auth data validated.
func NewRequest(pool *RequestPool, req *http.Request) *Request {
out := pool.sp.Get().(*Request)
cookies := req.Cookies()
headers := req.Header
out.Metadata = make(map[string]any, len(cookies))
for _, cookie := range cookies {
out.Metadata[cookie.Name] = cookie.Value
}
for hname, hval := range headers {
out.Metadata[hname] = hval
}
reqID := uuid.NewString()
out.ID = reqID
return out
}
func GetValue[T any](vals map[string]any, key string) (T, error) {
var out T
if vals == nil {
return out, fmt.Errorf("nil vals map")
}
rawVal, ok := vals[key]
if !ok {
return out, fmt.Errorf("value not found in resolve values set")
}
out, ok = rawVal.(T)
if !ok {
return out, fmt.Errorf("type of a value is unexpected")
}
return out, nil
}