2 Star 1 Fork 1

mosache / YFrame

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
context.go 1.35 KB
一键复制 编辑 原始数据 按行查看 历史
ヤ沒脩袮兲︶ 提交于 2023-10-26 18:29 . temp
package rest
import (
"errors"
"fmt"
"html/template"
"net/http"
"reflect"
)
type Context struct {
Req *http.Request
Resp http.ResponseWriter
Params map[string]string
RespData []byte
RespStatusCode int
MatchedRoute string
}
func (c *Context) Render(ts *template.Template, name string, data any) {
t := ts.Lookup(fmt.Sprintf("%s.gohtml", name))
c.Resp.Header().Set("Content-Type", "text/html")
c.Resp.WriteHeader(200)
t.Execute(c.Resp, data)
}
func (c *Context) RespString(msg string, statusCode int) {
c.Resp.WriteHeader(statusCode)
c.Resp.Write([]byte(msg))
}
func (c *Context) Redirect(url string) {
http.Redirect(c.Resp, c.Req, url, http.StatusTemporaryRedirect)
}
func (c *Context) Bind(data any) error {
req := c.Req
err := req.ParseForm()
if err != nil {
return err
}
typ := reflect.TypeOf(data)
if typ.Kind() != reflect.Pointer {
return errors.New("pointer needed")
}
for typ.Kind() != reflect.Struct {
typ = typ.Elem()
}
val := reflect.ValueOf(data).Elem()
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
if field.CanSet() {
sf := typ.Field(i)
fValue, ok := sf.Tag.Lookup("form")
if ok {
getValue := req.PostForm.Get(fValue)
field.Set(reflect.ValueOf(getValue))
}
}
}
return nil
}
func (c *Context) Query(key string) string {
qs := c.Req.URL.Query()
return qs.Get(key)
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/mosache/YFrame.git
git@gitee.com:mosache/YFrame.git
mosache
YFrame
YFrame
v0.1.82

搜索帮助

344bd9b3 5694891 D2dac590 5694891