nf/ctx.go
2024-01-11 22:29:30 +08:00

66 lines
1.1 KiB
Go

package nf
import (
"net/http"
)
type Map map[string]interface{}
type Ctx struct {
// origin objects
Writer http.ResponseWriter
Request *http.Request
// request info
path string
Method string
// response info
StatusCode int
params map[string]string
index int
handlers []HandlerFunc
locals map[string]any
}
func newContext(writer http.ResponseWriter, request *http.Request) *Ctx {
return &Ctx{
Writer: writer,
Request: request,
path: request.URL.Path,
Method: request.Method,
index: -1,
locals: map[string]any{},
handlers: make([]HandlerFunc, 0),
}
}
func (c *Ctx) Locals(key string, value ...any) any {
data := c.locals[key]
if len(value) > 0 {
c.locals[key] = value[0]
}
return data
}
func (c *Ctx) Path(overWrite ...string) string {
path := c.Request.URL.Path
if len(overWrite) > 0 && overWrite[0] != "" {
c.Request.URL.Path = overWrite[0]
}
return path
}
func (c *Ctx) Next() error {
c.index++
s := len(c.handlers)
for ; c.index < s; c.index++ {
if err := c.handlers[c.index](c); err != nil {
return err
}
}
return nil
}