[feat] RawResponse 支持

This commit is contained in:
what 2023-10-31 16:08:15 +08:00
parent 19c6d7d183
commit 2e6c86ddaa

View File

@ -12,6 +12,9 @@ import (
"github.com/samber/lo"
)
type RawResponse struct {
raw []byte
}
type JsonResponse struct {
raw []byte
}
@ -37,6 +40,20 @@ var wsUpgrader = websocket.Upgrader{
},
}
func (this RawResponse) Get(path ...string) contracts.GlobalParams {
return lo.Ternary(len(path) == 0, NewGlobalParam(string(this.raw), nil), NewGlobalParam(string(this.raw), nil).Get(strings.Join(path, ".")))
}
func (this RawResponse) Send(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Upgrade") != "" && strings.ToLower(r.Header.Get("Upgrade")) == "websocket" {
c, _ := wsUpgrader.Upgrade(w, r, nil)
c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, string(this.raw)))
c.Close()
} else {
w.Write(this.raw)
}
}
func (this JsonResponse) Get(path ...string) contracts.GlobalParams {
return lo.Ternary(len(path) == 0, NewGlobalParam(string(this.raw), nil), NewGlobalParam(string(this.raw), nil).Get(strings.Join(path, ".")))
}
@ -113,6 +130,10 @@ func (this FileResponse) Send(w http.ResponseWriter, r *http.Request) {
}
}
func NewRawResponse(b []byte) contracts.HttpResponse {
return &RawResponse{raw: b}
}
func NewJsonResponse(b []byte) contracts.HttpResponse {
return &JsonResponse{raw: b}
}