107 lines
2.1 KiB
Go
107 lines
2.1 KiB
Go
package serverevents
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
)
|
|
|
|
type Context struct {
|
|
method string
|
|
eventName string
|
|
eventData any
|
|
meta map[string]any
|
|
eventBefore *Event
|
|
emitter *EventEmitter
|
|
w http.ResponseWriter
|
|
r *http.Request
|
|
}
|
|
|
|
func NewServerEventContext(w http.ResponseWriter, r *http.Request, eventBefore *Event) *Context {
|
|
context := Context{
|
|
eventBefore: eventBefore,
|
|
meta: make(map[string]any),
|
|
w: w,
|
|
r: r,
|
|
emitter: GetEventEmitter(),
|
|
}
|
|
context.method = r.Method
|
|
context.eventName = r.PathValue("event")
|
|
return &context
|
|
}
|
|
|
|
func (ctx *Context) Emit(event Event) {
|
|
if ctx.emitter == nil {
|
|
return
|
|
}
|
|
ctx.emitter.Emit(event)
|
|
}
|
|
|
|
func (ctx *Context) GetRequest() *http.Request {
|
|
return ctx.r
|
|
}
|
|
|
|
func (ctx *Context) GetResponseWriter() http.ResponseWriter {
|
|
return ctx.w
|
|
}
|
|
|
|
func (ctx *Context) GetEventName() string {
|
|
return ctx.eventName
|
|
}
|
|
|
|
func (ctx *Context) GetMethod() string {
|
|
return ctx.method
|
|
}
|
|
|
|
func (ctx *Context) GetHeaderValue(key string) string {
|
|
return ctx.r.Header.Get(key)
|
|
}
|
|
|
|
func (ctx *Context) Send(status int, contentType string, data []byte) {
|
|
if len(contentType) > 0 {
|
|
ctx.w.Header().Add("Content-Type", contentType)
|
|
}
|
|
ctx.w.WriteHeader(status)
|
|
ctx.w.Write(data)
|
|
}
|
|
|
|
func GetEventData[T any](ctx *Context) (T, error) {
|
|
var result T
|
|
var ok bool
|
|
if ctx.eventData != nil {
|
|
result, ok = ctx.eventData.(T)
|
|
if ok {
|
|
return result, nil
|
|
}
|
|
}
|
|
stream, readBodyErr := io.ReadAll(ctx.r.Body)
|
|
if readBodyErr != nil {
|
|
return result, readBodyErr
|
|
}
|
|
parseErr := json.Unmarshal(stream, &result)
|
|
if parseErr != nil {
|
|
return result, parseErr
|
|
}
|
|
ctx.eventData = result
|
|
return result, nil
|
|
}
|
|
|
|
func SetContextValue[T any](ctx *Context, key string, value T) {
|
|
ctx.meta[key] = value
|
|
}
|
|
|
|
func GetContextValue[T any](ctx *Context, key string) (T, error) {
|
|
var result T
|
|
var ok bool
|
|
tmp := ctx.meta[key]
|
|
if tmp == nil {
|
|
return result, fmt.Errorf("no value with key %s found", key)
|
|
}
|
|
result, ok = tmp.(T)
|
|
if !ok {
|
|
return result, fmt.Errorf("value has expect to be a other DataType %s", key)
|
|
}
|
|
return result, nil
|
|
}
|