1 Star 0 Fork 0

ghosind/dolphin

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
response.go 2.03 KB
一键复制 编辑 原始数据 按行查看 历史
ghosind 提交于 2021-11-08 00:26 +08:00 . Move req and resp pools into app engine.
package dolphin
import (
"bytes"
"errors"
"io"
"net/http"
)
// Response is the HTTP response wrapper.
type Response struct {
body *bytes.Buffer
cookies []*http.Cookie
header http.Header
statusCode int
}
// reset resets response object to initial state.
func (resp *Response) reset() {
resp.body = &bytes.Buffer{}
resp.cookies = make([]*http.Cookie, 0)
resp.header = make(http.Header)
resp.statusCode = http.StatusOK
}
// write writes response to the specific HTTP response writer.
func (resp *Response) write(rw http.ResponseWriter) {
// Add cookies to response.
if len(resp.cookies) > 0 {
for _, cookie := range resp.cookies {
if cookie == nil {
continue
}
resp.AddHeader(HeaderSetCookie, cookie.String())
}
}
// Write response header.
for key, val := range resp.header {
rw.Header()[key] = val
}
// Set response status code to OK if not set or it's invalid.
if resp.statusCode <= 0 || resp.statusCode > 999 {
resp.statusCode = http.StatusOK
}
// Set response status code
rw.WriteHeader(resp.statusCode)
// Write response body.
io.Copy(rw, resp.body)
}
// SetBody sets response body.
func (resp *Response) SetBody(data []byte) (int, error) {
return resp.body.Write(data)
}
// AddCookies adds cookies setting to response, it will set response HTTP
// header "Set-Cookie" field.
func (resp *Response) AddCookies(cookies ...*http.Cookie) {
resp.cookies = append(resp.cookies, cookies...)
}
// AddHeader adds value to the specific response HTTP header field.
func (resp *Response) AddHeader(key, val string) {
resp.header.Add(key, val)
}
// SetHeader sets the specific response HTTP header field.
func (resp *Response) SetHeader(key, val string) {
resp.header.Set(key, val)
}
// SetStatusCode sets the status code of the response.
func (resp *Response) SetStatusCode(code int) error {
if code <= 0 || code > 999 {
return errors.New("invalid status code")
}
resp.statusCode = code
return nil
}
// StatusCode gets the response status code.
func (resp *Response) StatusCode() int {
return resp.statusCode
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/ghosind/dolphin.git
git@gitee.com:ghosind/dolphin.git
ghosind
dolphin
dolphin
main

搜索帮助