nf/ctx.go

97 lines
1.8 KiB
Go
Raw Normal View History

2024-01-10 20:26:19 +08:00
package nf
import (
2024-01-11 18:16:41 +08:00
"encoding/json"
"fmt"
2024-01-10 20:26:19 +08:00
"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
Path string
Method string
// response info
2024-01-10 20:26:19 +08:00
StatusCode int
2024-01-11 18:16:41 +08:00
Params map[string]string
index int
handlers []HandlerFunc
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 18:16:41 +08:00
Writer: writer,
Request: request,
Path: request.URL.Path,
Method: request.Method,
index: -1,
2024-01-10 20:26:19 +08:00
}
}
2024-01-11 18:16:41 +08:00
func (c *Ctx) Form(key string) string {
return c.Request.FormValue(key)
}
func (c *Ctx) Query(key string) string {
return c.Request.URL.Query().Get(key)
}
func (c *Ctx) Status(code int) {
c.StatusCode = code
c.Writer.WriteHeader(code)
}
func (c *Ctx) SetHeader(key string, value string) {
c.Writer.Header().Set(key, value)
}
func (c *Ctx) SendString(data string) error {
c.SetHeader("Content-Type", "text/plain")
_, err := c.Write([]byte(data))
return err
2024-01-10 20:26:19 +08:00
}
2024-01-11 18:16:41 +08:00
func (c *Ctx) Writef(format string, values ...interface{}) (int, error) {
c.SetHeader("Content-Type", "text/plain")
return c.Writer.Write([]byte(fmt.Sprintf(format, values...)))
}
func (c *Ctx) JSON(data interface{}) error {
c.SetHeader("Content-Type", "application/json")
encoder := json.NewEncoder(c.Writer)
if err := encoder.Encode(data); err != nil {
return err
2024-01-10 20:26:19 +08:00
}
2024-01-11 18:16:41 +08:00
return nil
2024-01-10 20:26:19 +08:00
}
2024-01-11 18:16:41 +08:00
func (c *Ctx) Write(data []byte) (int, error) {
return c.Writer.Write(data)
2024-01-10 20:26:19 +08:00
}
2024-01-11 18:16:41 +08:00
func (c *Ctx) HTML(html string) error {
c.SetHeader("Content-Type", "text/html")
_, err := c.Writer.Write([]byte(html))
return err
}
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
}