88 lines
1.4 KiB
Go
88 lines
1.4 KiB
Go
package response
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"ruben/inventory2/internal/site/redirect"
|
|
)
|
|
|
|
type (
|
|
jsonRes struct {
|
|
body any
|
|
res Response
|
|
}
|
|
)
|
|
|
|
var _ Response = jsonRes{}
|
|
|
|
func JSON(body any) Response {
|
|
return jsonRes{
|
|
body: body,
|
|
}
|
|
}
|
|
|
|
func (j jsonRes) String() string {
|
|
if j.res != nil {
|
|
return fmt.Sprintf(`{"body": %q, "nested": %s}`, j.body, j.res)
|
|
}
|
|
return fmt.Sprintf(`{"body": %q}`, j.body)
|
|
}
|
|
|
|
func (j jsonRes) wrap(res Response) Response {
|
|
j.res = res
|
|
return j
|
|
}
|
|
|
|
func (j jsonRes) Status(code int) Response {
|
|
return Status(code).wrap(j)
|
|
}
|
|
|
|
func (j jsonRes) Redirect(code redirect.Code, to string) Response {
|
|
return Redirect(code, to).wrap(j)
|
|
}
|
|
|
|
func (j jsonRes) JSON(body any) Response {
|
|
j.body = body
|
|
return j
|
|
}
|
|
|
|
func (j jsonRes) Body(body io.ReadCloser) Response {
|
|
return Body(body).wrap(j)
|
|
}
|
|
|
|
func (j jsonRes) Cookie(ck http.Cookie) Response {
|
|
return Cookie(ck).wrap(j)
|
|
}
|
|
|
|
func (j jsonRes) getStatus() (int, bool) {
|
|
if j.res == nil {
|
|
return 0, false
|
|
}
|
|
|
|
return j.res.getStatus()
|
|
}
|
|
|
|
func (j jsonRes) getRedirect() (code redirect.Code, to string, ok bool) {
|
|
if j.res == nil {
|
|
return 0, "", false
|
|
}
|
|
|
|
return j.res.getRedirect()
|
|
}
|
|
|
|
func (j jsonRes) getBody() (body io.ReadCloser, ok bool, err error) {
|
|
buf := new(bytes.Buffer)
|
|
return io.NopCloser(buf), true, json.NewEncoder(buf).Encode(j.body)
|
|
}
|
|
|
|
func (j jsonRes) getCookies() []http.Cookie {
|
|
if j.res != nil {
|
|
return j.res.getCookies()
|
|
}
|
|
|
|
return nil
|
|
}
|