Moonshark/core/runner/Response.go
2025-04-09 19:03:35 -05:00

77 lines
1.6 KiB
Go

package runner
import (
"sync"
"github.com/valyala/fasthttp"
)
// Response represents a unified response from script execution
type Response struct {
// Basic properties
Body any // Body content (any type)
Metadata map[string]any // Additional metadata
// HTTP specific properties
Status int // HTTP status code
Headers map[string]string // HTTP headers
Cookies []*fasthttp.Cookie // HTTP cookies
// Session information
SessionID string // Session ID
SessionData map[string]any // Session data
SessionModified bool // Whether session was modified
}
// Response pool to reduce allocations
var responsePool = sync.Pool{
New: func() any {
return &Response{
Status: 200,
Headers: make(map[string]string, 8),
Metadata: make(map[string]any, 8),
Cookies: make([]*fasthttp.Cookie, 0, 4),
SessionData: make(map[string]any, 8),
}
},
}
// NewResponse creates a new response object from the pool
func NewResponse() *Response {
return responsePool.Get().(*Response)
}
// Release returns a response to the pool after cleaning it
func ReleaseResponse(resp *Response) {
if resp == nil {
return
}
// Reset fields to default values
resp.Body = nil
resp.Status = 200
// Clear maps
for k := range resp.Headers {
delete(resp.Headers, k)
}
for k := range resp.Metadata {
delete(resp.Metadata, k)
}
for k := range resp.SessionData {
delete(resp.SessionData, k)
}
// Clear cookies
resp.Cookies = resp.Cookies[:0]
// Reset session info
resp.SessionID = ""
resp.SessionModified = false
// Return to pool
responsePool.Put(resp)
}