nf/ctx.go

66 lines
1.1 KiB
Go
Raw Normal View History

2024-01-10 20:26:19 +08:00
package nf
import (
"net/http"
)
2024-01-11 18:16:41 +08:00
type Map map[string]interface{}
2024-01-10 20:26:19 +08:00
type Ctx struct {
2024-01-11 18:16:41 +08:00
// origin objects
Writer http.ResponseWriter
Request *http.Request
// request info
2024-01-11 22:29:30 +08:00
path string
2024-01-11 18:16:41 +08:00
Method string
// response info
2024-01-10 20:26:19 +08:00
StatusCode int
2024-01-11 18:16:41 +08:00
2024-01-11 22:29:30 +08:00
params map[string]string
2024-01-11 18:16:41 +08:00
index int
handlers []HandlerFunc
2024-01-11 22:29:30 +08:00
locals map[string]any
2024-01-10 20:26:19 +08:00
}
2024-01-11 18:16:41 +08:00
func newContext(writer http.ResponseWriter, request *http.Request) *Ctx {
2024-01-10 20:26:19 +08:00
return &Ctx{
2024-01-11 22:29:30 +08:00
Writer: writer,
Request: request,
path: request.URL.Path,
Method: request.Method,
index: -1,
locals: map[string]any{},
handlers: make([]HandlerFunc, 0),
2024-01-10 20:26:19 +08:00
}
}
2024-01-11 22:29:30 +08:00
func (c *Ctx) Locals(key string, value ...any) any {
data := c.locals[key]
if len(value) > 0 {
c.locals[key] = value[0]
2024-01-10 20:26:19 +08:00
}
2024-01-11 18:16:41 +08:00
2024-01-11 22:29:30 +08:00
return data
2024-01-10 20:26:19 +08:00
}
2024-01-11 22:29:30 +08:00
func (c *Ctx) Path(overWrite ...string) string {
path := c.Request.URL.Path
if len(overWrite) > 0 && overWrite[0] != "" {
c.Request.URL.Path = overWrite[0]
}
2024-01-10 20:26:19 +08:00
2024-01-11 22:29:30 +08:00
return path
2024-01-11 18:16:41 +08:00
}
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
2024-01-10 20:26:19 +08:00
}