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 {
|
2017-12-26 15:41:10 +08:00
|
|
|
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
|
2017-12-26 15:41:10 +08:00
|
|
|
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()
|
2017-12-14 17:32:51 +08:00
|
|
|
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 13:31:07 +08:00
|
|
|
// 获取当前缓冲区中的数据
|
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-13 11:36:29 +08:00
|
|
|
// 输出缓冲区数据到客户端
|
|
|
|
func (r *ServerResponse) Output() {
|
2017-12-26 13:31:07 +08:00
|
|
|
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
|
|
|
}
|