1 Star 0 Fork 0

Wsage / go-framework

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
server_http_ctx.go 2.26 KB
一键复制 编辑 原始数据 按行查看 历史
王少奇 提交于 2021-09-09 16:50 . 新增 multipartform的解析
package httpserver
import (
"context"
"encoding/json"
"github.com/julienschmidt/httprouter"
"mime/multipart"
"net/http"
"net/url"
)
type Ctx struct {
httpContext context.Context
writer http.ResponseWriter
request *http.Request
routerParams httprouter.Params
IHttpResponse
}
func NewCtx(writer http.ResponseWriter, request *http.Request) *Ctx {
resp := NewHttpResponse(writer)
ctx := &Ctx{
httpContext: request.Context(),
writer: writer,
request: request,
IHttpResponse: resp,
}
return ctx
}
func (ctx *Ctx) _setRouterParams(params httprouter.Params) {
ctx.routerParams = params
}
func (ctx *Ctx) Context() context.Context {
return ctx.httpContext
}
func (ctx *Ctx) WithValue(key, val interface{}) {
ctx.httpContext = context.WithValue(ctx.httpContext, key, val)
}
func (ctx *Ctx) Form() url.Values {
r := ctx.request
form := url.Values{}
r.ParseForm()
form = r.Form
return form
}
func (ctx *Ctx) FormJson(stc interface{}) error {
r := ctx.request
contentType := r.Header.Get("Content-Type")
switch contentType {
case "application/json":
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&stc)
if err != nil {
return err
}
default:
}
return nil
}
func (ctx *Ctx) FormMultipart() (map[string][]string, map[string][]*multipart.FileHeader, error) {
r := ctx.request
err := r.ParseMultipartForm(128)
if err != nil {
return nil, nil, err
}
return r.MultipartForm.Value, r.MultipartForm.File, nil
}
func (ctx *Ctx) Value(key interface{}) interface{} {
return ctx.httpContext.Value(key)
}
func (ctx *Ctx) SetResponseHandler(response IHttpResponse) {
ctx.IHttpResponse = response
}
func (ctx *Ctx) Writer() http.ResponseWriter {
return ctx.writer
}
func (ctx *Ctx) Request() *http.Request {
return ctx.request
}
func (ctx *Ctx) Param(name string) string {
return ctx.routerParams.ByName(name)
}
func (ctx *Ctx) WriteHeader(code int) {
ctx.writer.WriteHeader(code)
}
func (ctx *Ctx) Header() http.Header {
return ctx.writer.Header()
}
func (ctx *Ctx) Write(resp []byte) (int, error) {
return ctx.writer.Write(resp)
}
func (ctx *Ctx) WriteStr(resp string) (int, error) {
return ctx.writer.Write([]byte(resp))
}
func (ctx *Ctx) Authorization() string {
return ctx.request.Header.Get("Authorization")
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/scottq/go-framework.git
git@gitee.com:scottq/go-framework.git
scottq
go-framework
go-framework
v1.1.32

搜索帮助

344bd9b3 5694891 D2dac590 5694891