feat: middleware reach, response writer interfaces, and CORS fixes
- Run global middleware for all requests, including OPTIONS preflights, NotFound, and MethodNotAllowed — previously bypassed by httprouter's internal handling - Implement Hijacker, Flusher, and Pusher on the response writer for WebSocket, SSE, and HTTP/2 push support - Fix CORS: echo a single matching origin, handle AllowCredentials with wildcard, append Vary: Origin - Logger logs from a defer to capture correct status on panicked requests - Static and StaticFS accept route middleware; add Context.AddHeader; warn on NotFound handler override
This commit is contained in:
23
context.go
23
context.go
@@ -16,10 +16,9 @@ import (
|
||||
type contextKey string
|
||||
|
||||
type Context struct {
|
||||
ctx context.Context
|
||||
w *responseWriter
|
||||
r *http.Request
|
||||
p httprouter.Params
|
||||
w *responseWriter
|
||||
r *http.Request
|
||||
p httprouter.Params
|
||||
}
|
||||
|
||||
func (c *Context) GetRequest() *http.Request {
|
||||
@@ -35,7 +34,7 @@ func (c *Context) GetStatusCode() int {
|
||||
}
|
||||
|
||||
func (c *Context) GetContext() context.Context {
|
||||
return c.ctx
|
||||
return c.r.Context()
|
||||
}
|
||||
|
||||
func (c *Context) GetPathParam(key string) string {
|
||||
@@ -47,11 +46,15 @@ func (c *Context) GetQueryParam(key string) string {
|
||||
}
|
||||
|
||||
func (c *Context) SetValue(key string, v any) {
|
||||
c.ctx = context.WithValue(c.ctx, contextKey(key), v)
|
||||
c.r = c.r.WithContext(context.WithValue(c.r.Context(), contextKey(key), v))
|
||||
}
|
||||
|
||||
func (c *Context) GetValue(key string) any {
|
||||
return c.ctx.Value(contextKey(key))
|
||||
return c.r.Context().Value(contextKey(key))
|
||||
}
|
||||
|
||||
func (c *Context) AddHeader(key, v string) {
|
||||
c.w.Header().Add(key, v)
|
||||
}
|
||||
|
||||
func (c *Context) SetHeader(key, v string) {
|
||||
@@ -126,20 +129,20 @@ func (c *Context) WriteBytes(statusCode int, v []byte) error {
|
||||
}
|
||||
|
||||
func (c *Context) WriteString(statusCode int, v string) error {
|
||||
c.w.Header().Set("Content-Type", "text/plain")
|
||||
c.w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
c.w.WriteHeader(statusCode)
|
||||
_, err := c.w.Write([]byte(v))
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Context) WriteJSON(statusCode int, v any) error {
|
||||
c.w.Header().Set("Content-Type", "application/json")
|
||||
c.w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
c.w.WriteHeader(statusCode)
|
||||
return json.NewEncoder(c.w).Encode(v)
|
||||
}
|
||||
|
||||
func (c *Context) WriteXML(statusCode int, v any) error {
|
||||
c.w.Header().Set("Content-Type", "application/xml")
|
||||
c.w.Header().Set("Content-Type", "application/xml; charset=utf-8")
|
||||
c.w.WriteHeader(statusCode)
|
||||
return xml.NewEncoder(c.w).Encode(v)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user