1 Star 0 Fork 0

tom / xx

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
stream.go 1.79 KB
一键复制 编辑 原始数据 按行查看 历史
tom 提交于 2023-08-08 07:02 . update web/stream.go.
package web
import (
"encoding/json"
"io/ioutil"
"net/http"
)
type Stream struct {
r *http.Request
w http.ResponseWriter
ls []string
trade map[string]interface{}
SaveLog func(ls []string)
}
func (s *Stream) RspJson(code int, data interface{}) {
out := map[string]interface{}{
"Code": code,
}
switch data.(type) {
case error:
out["Msg"] = data.(error).Error()
default:
out["Msg"] = "Success"
out["Data"] = data
}
bs, err := json.Marshal(out)
if err != nil {
s.out([]byte(err.Error()))
return
}
s.out(bs)
}
func (s *Stream) Write(bs []byte) {
s.out(bs)
}
// out 输出
func (s *Stream) out(bs []byte) {
_, err := s.w.Write(bs)
if err != nil {
s.Log(err.Error())
}
s.SaveLog(s.ls)
}
func (s *Stream) Log(info string) {
s.ls = append(s.ls, info)
}
func (s *Stream) binPost(param interface{}) error {
bs, err := ioutil.ReadAll(s.r.Body)
if err != nil {
return err
}
return json.Unmarshal(bs, param)
}
func (s *Stream) binGet(param interface{}) error {
var m = map[string]string{}
for k, v := range s.r.URL.Query() {
if len(v) == 1 {
m[k] = v[0]
}
}
bs, _ := json.Marshal(m)
return json.Unmarshal(bs, param)
}
func (s *Stream) BinParam(param interface{}) error {
switch s.r.Method {
case "get", "GET":
return s.binGet(param)
default:
return s.binPost(param)
}
}
func (s *Stream) GetHttpHeader(key string) string {
return s.r.Header.Get(key)
}
func (s *Stream) GetReader() *http.Request {
return s.r
}
func (s *Stream) GetWrite() http.ResponseWriter {
return s.w
}
func (s *Stream) SetTrade(key string, i interface{}) {
if s.trade == nil {
s.trade = map[string]interface{}{}
}
s.trade[key] = i
}
func (s *Stream) GetTrade(key string) interface{} {
if s.trade == nil {
s.trade = map[string]interface{}{}
}
return s.trade[key]
}
1
https://gitee.com/t137675423/xx.git
git@gitee.com:t137675423/xx.git
t137675423
xx
xx
b94440794f46

搜索帮助