gf/g/net/ghttp/http_server_response.go

78 lines
1.9 KiB
Go
Raw Normal View History

2017-12-07 14:57:16 +08:00
package ghttp
import (
"net/http"
"gitee.com/johng/gf/g/encoding/gjson"
2017-12-13 11:36:29 +08:00
"sync"
2017-12-07 14:57:16 +08:00
)
// 服务端请求返回对象
type ServerResponse struct {
http.ResponseWriter
2017-12-13 11:36:29 +08:00
bufmu sync.RWMutex // 缓冲区互斥锁
buffer []byte // 每个请求的返回数据缓冲区
2017-12-07 14:57:16 +08:00
}
// 返回的固定JSON数据结构
type ResponseJson struct {
Result int `json:"result"` // 标识消息状态
Message string `json:"message"` // 消息使用string存储
Data []byte `json:"data"` // 二进制数据(不管什么数据结构)
2017-12-07 14:57:16 +08:00
}
2017-12-08 09:50:11 +08:00
// 返回信息(byte)
2017-12-07 17:34:51 +08:00
func (r *ServerResponse) Write(content []byte) {
2017-12-13 11:36:29 +08:00
r.bufmu.Lock()
defer r.bufmu.Unlock()
r.buffer = append(r.buffer, content...)
2017-12-07 14:57:16 +08:00
}
2017-12-08 09:50:11 +08:00
// 返回信息(string)
func (r *ServerResponse) WriteString(content string) {
2017-12-13 11:36:29 +08:00
r.bufmu.Lock()
defer r.bufmu.Unlock()
r.buffer = append(r.buffer, content...)
2017-12-08 09:50:11 +08:00
}
2017-12-07 14:57:16 +08:00
// 返回固定格式的json
func (r *ServerResponse) WriteJson(result int, message string, data []byte) error {
2017-12-13 11:36:29 +08:00
r.Header().Set("Content-Type", "application/json")
r.bufmu.Lock()
defer r.bufmu.Unlock()
if jsonstr, err := gjson.Encode(ResponseJson{ result, message, data }); err != nil {
return err
} else {
r.buffer = append(r.buffer, jsonstr...)
}
return nil
2017-12-07 14:57:16 +08:00
}
2017-12-08 09:50:11 +08:00
// 返回内容编码
func (r *ServerResponse) WriteHeaderEncoding(encoding string) {
r.Header().Set("Content-Type", "text/plain; charset=" + encoding)
}
// 获取当前缓冲区中的数据
2017-12-26 10:13:49 +08:00
func (r *ServerResponse) Buffer() []byte {
r.bufmu.RLock()
defer r.bufmu.RUnlock()
return r.buffer
}
2017-12-28 15:21:25 +08:00
// 清空缓冲区内容
func (r *ServerResponse) ClearBuffer() {
r.bufmu.Lock()
defer r.bufmu.Unlock()
r.buffer = make([]byte, 0)
}
2017-12-13 11:36:29 +08:00
// 输出缓冲区数据到客户端
2017-12-28 15:21:25 +08:00
func (r *ServerResponse) OutputBuffer() {
r.bufmu.Lock()
defer r.bufmu.Unlock()
if len(r.buffer) > 0 {
r.ResponseWriter.Write(r.buffer)
r.buffer = make([]byte, 0)
}
2017-12-13 11:36:29 +08:00
}