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"`
|
|
|
|
Data interface{} `json:"data"`
|
|
|
|
}
|
|
|
|
|
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-08 09:50:11 +08:00
|
|
|
func (r *ServerResponse) WriteJson(result int, message string, data interface{}) {
|
2017-12-13 11:36:29 +08:00
|
|
|
r.Header().Set("Content-Type", "application/json")
|
|
|
|
r.bufmu.Lock()
|
|
|
|
defer r.bufmu.Unlock()
|
|
|
|
r.buffer = append(r.buffer, gjson.Encode(ResponseJson{ result, message, data })...)
|
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-13 11:36:29 +08:00
|
|
|
// 输出缓冲区数据到客户端
|
|
|
|
func (r *ServerResponse) Output() {
|
|
|
|
r.bufmu.RLock()
|
|
|
|
defer r.bufmu.RUnlock()
|
|
|
|
r.ResponseWriter.Write(r.buffer)
|
|
|
|
}
|