2 Star 0 Fork 0

mirrors_alecthomas/rest

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
default_protocol.go 1.66 KB
一键复制 编辑 原始数据 按行查看 历史
Alec Thomas 提交于 2018-06-09 12:31 +08:00 . Initial commit.
package rest
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
)
// DefaultProtocol implements a default JSON protocol with a standard error format.
var DefaultProtocol Protocol = defaultProtocol{}
type defaultProtocol struct{}
func (d defaultProtocol) DecodeClientRequest(req *http.Request, v interface{}) error {
return json.NewDecoder(req.Body).Decode(v)
}
func (d defaultProtocol) EncodeServerResponse(req *http.Request, w http.ResponseWriter, code int, err error, v interface{}) error {
if err != nil {
response, ok := err.(*ErrorResponse)
if ok {
code = response.Status
} else {
if code == 0 {
code = http.StatusInternalServerError
}
response = &ErrorResponse{Status: code, Message: err.Error()}
}
return d.EncodeServerResponse(req, w, code, nil, response)
}
if code == 0 {
if req.Method == "POST" {
code = http.StatusCreated
} else if v == nil {
code = http.StatusNoContent
} else {
code = http.StatusOK
}
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(code)
return json.NewEncoder(w).Encode(v)
}
func (d defaultProtocol) EncodeClientRequest(req *http.Request, v interface{}) error {
if v == nil {
return nil
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
buf := &bytes.Buffer{}
req.Body = ioutil.NopCloser(buf)
return json.NewEncoder(buf).Encode(v)
}
func (d defaultProtocol) DecodeServerResponse(resp *http.Response, v interface{}) error {
if resp.StatusCode < 400 {
return json.NewDecoder(resp.Body).Decode(v)
}
errr := &ErrorResponse{}
err := json.NewDecoder(resp.Body).Decode(errr)
if err != nil {
return err
}
return errr
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/mirrors_alecthomas/rest.git
git@gitee.com:mirrors_alecthomas/rest.git
mirrors_alecthomas
rest
rest
master

搜索帮助