92 lines
1.7 KiB
Go
92 lines
1.7 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
|
|
}
|
|
|
|
func (p *RequestPool) Get() *Request {
|
|
r, _ := p.sp.Get().(*Request)
|
|
return r
|
|
}
|
|
|
|
func (p *RequestPool) Put(r *Request) {
|
|
r.ID = ""
|
|
r.Metadata = make(map[string]any)
|
|
r.ResolveValues = sync.Map{}
|
|
r.Session = nil
|
|
r.User = nil
|
|
r.Body = nil
|
|
p.sp.Put(r)
|
|
}
|
|
|
|
func NewRequestPool() *RequestPool {
|
|
return &RequestPool{
|
|
sp: sync.Pool{
|
|
New: func() any {
|
|
return &Request{
|
|
ResolveValues: sync.Map{},
|
|
Metadata: make(map[string]any),
|
|
}
|
|
},
|
|
},
|
|
}
|
|
}
|
|
|
|
type Request struct {
|
|
ID string
|
|
Session *models.Session
|
|
User *models.User
|
|
ResolveValues sync.Map
|
|
Metadata map[string]any
|
|
Body []byte
|
|
}
|
|
|
|
// NewRequestFromHttp builds a new *Request struct from raw http Request. No auth data validated.
|
|
func NewRequestFromHttp(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
|
|
}
|