美文网首页
抽象response、request到context中

抽象response、request到context中

作者: __missing | 来源:发表于2021-06-25 18:22 被阅读0次

将response、request抽象到context更方便操作。context主要负责读取请求数据,返回响应数据

type Context struct {
    Writer http.ResponseWriter
    Req *http.Request

    Method string
    Path string
    Content []byte //这个用来存储Req.Body
}

func (c *Context) Input(key string) interface{} {
    inputAll := c.inputAll()
    if value, ok := inputAll.(map[string]interface{}); ok {
        if res,ok := value[key]; ok {
            return res
        }
        return ""
    }

    if value, ok := inputAll.(url.Values); ok {
        if res,ok := value[key]; ok {
            return res[0]
        }
        return ""
    }
    return inputAll
}


func (c *Context) inputAll() interface{} {
    if c.Method == "GET" { //GET请求只需要获取query_string中的参数
        return c.Req.URL.Query()
    }

    switch c.Req.Header.Get("Content-Type") { 
    case "application/x-www-form-urlencoded" : 
        c.Req.ParseForm()
        return c.Req.Form
    case "application/json" :
        tmp := make(map[string]interface{})
        json.Unmarshal(c.Content, &tmp)
        return tmp
    default :
        s,_:=ioutil.ReadAll(c.Req.Body)
        return s
    }
}

func (c *Context) Json(status int, res map[string]interface{}) {
        c.SetHeader("Content-Type", "application/json")
        c.Status(status)
        encoder := json.NewEncoder(c.Writer)
        encoder.Encode(res)
}

func (c *Context) String(status int, format string, values ...interface{}) {
    c.SetHeader("Content-Type", "text/plain")
    c.Status(status)
    c.Writer.Write([]byte(fmt.Sprintf(format, values...)))
}

func (c *Context) Status(status int) {
    c.Writer.WriteHeader(status)
}

func (c *Context) SetHeader(key string, value string) {
    c.Writer.Header().Set(key, value)
}

func (t *test) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    content,_ := ioutil.ReadAll(r.Body)
    cxt := &Context{
        Writer: w,
        Req: r,

        Method: r.Method,
        Path: r.URL.Path,

        Content: content,
    }
    key := r.Method + "-" + r.URL.Path
    if handle, ok := t.router[key]; ok {
        handle(cxt)

    } else {
        w.WriteHeader(http.StatusNotFound)
        w.Write([]byte("not found"))
    }
}


func main() {
    t := new(test)
    t.router = make(map[string]HandlerFunc)

    t.GET("/test", func(cxt *Context) {
        id := cxt.Input("id")
        if id == "5" {
            res := make(map[string]interface{})
            res["name"] = "杨欢欢"
            res["age"] = 18
            cxt.Json(http.StatusOK, res)
        } else {
            cxt.String(http.StatusNotFound, "Person not found")
        }
    })

    t.POST("/test", func(cxt *Context) {
        res := make(map[string]interface{})
        res["name"] = cxt.Input("name")
        res["age"] = cxt.Input("age")
        cxt.Json(http.StatusCreated, res)

    })

    http.ListenAndServe(":9999", t)
}

相关文章

网友评论

      本文标题:抽象response、request到context中

      本文链接:https://www.haomeiwen.com/subject/lqrwyltx.html