97 lines
1.8 KiB
Go
97 lines
1.8 KiB
Go
package nf
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"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
|
|
}
|
|
|
|
func newContext(writer http.ResponseWriter, request *http.Request) *Ctx {
|
|
return &Ctx{
|
|
Writer: writer,
|
|
Request: request,
|
|
Path: request.URL.Path,
|
|
Method: request.Method,
|
|
index: -1,
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (c *Ctx) Write(data []byte) (int, error) {
|
|
return c.Writer.Write(data)
|
|
}
|
|
|
|
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
|
|
}
|