Added middleware support

This commit is contained in:
2024-03-13 20:18:01 +01:00
parent 1bcf4794f5
commit e69a66aa31
9 changed files with 135 additions and 157 deletions

View File

@ -15,28 +15,38 @@ type Context interface {
Bytes([]byte) error
Error(messages ...any) error
Get(param string) string
Header(key string, value string)
Host() string
Method() string
Next() error
Path() string
Protocol() string
Reader(io.Reader) error
Request() Request
Response() Response
RequestHeader(key string) string
ResponseHeader(key string) string
Status(status int) Context
String(string) error
}
// ctx represents a request & response context.
type ctx struct {
request request
response response
paramNames [maxParams]string
paramValues [maxParams]string
paramCount int
request *http.Request
response http.ResponseWriter
server *Server
paramNames [maxParams]string
paramValues [maxParams]string
paramCount int
handlerCount int
}
// newContext returns a new context from the pool.
func newContext(req *http.Request, res http.ResponseWriter) *ctx {
func newContext(req *http.Request, res http.ResponseWriter, server *Server) *ctx {
ctx := contextPool.Get().(*ctx)
ctx.request.Request = req
ctx.response.ResponseWriter = res
ctx.request = req
ctx.response = res
ctx.server = server
ctx.paramCount = 0
ctx.handlerCount = 0
return ctx
}
@ -73,22 +83,53 @@ func (ctx *ctx) Get(param string) string {
return ""
}
// Next executes the next handler in the middleware chain.
func (ctx *ctx) Next() error {
ctx.handlerCount++
return ctx.server.handlers[ctx.handlerCount](ctx)
}
// RequestHeader returns the request header value for the given key.
func (ctx *ctx) RequestHeader(key string) string {
return ctx.request.Header.Get(key)
}
// ResponseHeader returns the response header value for the given key.
func (ctx *ctx) ResponseHeader(key string) string {
return ctx.response.Header().Get(key)
}
// Header sets the header value for the given key.
func (ctx *ctx) Header(key string, value string) {
ctx.response.Header().Set(key, value)
}
// Method returns the request method.
func (ctx *ctx) Method() string {
return ctx.request.Method
}
// Protocol returns the request protocol.
func (ctx *ctx) Protocol() string {
return ctx.request.Proto
}
// Host returns the requested host.
func (ctx *ctx) Host() string {
return ctx.request.Host
}
// Path returns the requested path.
func (ctx *ctx) Path() string {
return ctx.request.URL.Path
}
// Reader sends the contents of the io.Reader without creating an in-memory copy.
func (ctx *ctx) Reader(reader io.Reader) error {
_, err := io.Copy(ctx.response, reader)
return err
}
// Request returns the HTTP request.
func (ctx *ctx) Request() Request {
return &ctx.request
}
// Response returns the HTTP response.
func (ctx *ctx) Response() Response {
return &ctx.response
}
// Status sets the HTTP status of the response.
func (ctx *ctx) Status(status int) Context {
ctx.response.WriteHeader(status)