83 lines
2.0 KiB
Go
83 lines
2.0 KiB
Go
|
package gee
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
"net/http"
|
||
|
)
|
||
|
|
||
|
type H map[string]interface{}
|
||
|
|
||
|
type Context struct {
|
||
|
// origin objects 源对象
|
||
|
Writer http.ResponseWriter
|
||
|
Req *http.Request
|
||
|
// request info 请求信息
|
||
|
Path string
|
||
|
Method string
|
||
|
// response info 响应信息
|
||
|
StatusCode int
|
||
|
}
|
||
|
|
||
|
func newContext(w http.ResponseWriter, r *http.Request) *Context {
|
||
|
return &Context{
|
||
|
Writer: w,
|
||
|
Req: r,
|
||
|
Path: r.URL.Path,
|
||
|
Method: r.Method,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// PostForm 返回请求参数的值
|
||
|
func (c *Context) PostForm(key string) string {
|
||
|
return c.Req.FormValue(key)
|
||
|
}
|
||
|
|
||
|
// Query 返回请求参数的值
|
||
|
func (c *Context) Query(key string) string {
|
||
|
// Query方法解析RawQuery字段并返回其表示的Values类型键值对map。
|
||
|
// Get会获取key对应的值集的第一个值。如果没有对应key的值集会返回空字符串。
|
||
|
return c.Req.URL.Query().Get(key)
|
||
|
}
|
||
|
|
||
|
// Status 设置响应状态码
|
||
|
func (c *Context) Status(code int) {
|
||
|
c.StatusCode = code
|
||
|
c.Writer.WriteHeader(code)
|
||
|
}
|
||
|
|
||
|
// SetHeader 设置响应头
|
||
|
func (c *Context) SetHeader(key string, value string) {
|
||
|
c.Writer.Header().Set(key, value)
|
||
|
}
|
||
|
|
||
|
// String 设置 string 类型的响应体
|
||
|
func (c *Context) String(code int, format string, values ...interface{}) {
|
||
|
c.SetHeader("Content-Type", "text/plain")
|
||
|
c.Status(code)
|
||
|
_, _ = c.Writer.Write([]byte(fmt.Sprintf(format, values...)))
|
||
|
}
|
||
|
|
||
|
// Json 设置 json 类型的响应体
|
||
|
func (c *Context) Json(code int, obj interface{}) {
|
||
|
c.SetHeader("Content-Type", "application/json")
|
||
|
c.Status(code)
|
||
|
encoder := json.NewEncoder(c.Writer)
|
||
|
if err := encoder.Encode(obj); err != nil {
|
||
|
http.Error(c.Writer, err.Error(), http.StatusInternalServerError)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Data 设置 data 类型的响应体
|
||
|
func (c *Context) Data(code int, data []byte) {
|
||
|
c.Status(code)
|
||
|
_, _ = c.Writer.Write(data)
|
||
|
}
|
||
|
|
||
|
// Html 设置 html 类型的响应体
|
||
|
func (c *Context) Html(code int, html string) {
|
||
|
c.SetHeader("Content-Type", "text/html")
|
||
|
c.Status(code)
|
||
|
_, _ = c.Writer.Write([]byte(html))
|
||
|
}
|