102 lines
1.6 KiB
Go
102 lines
1.6 KiB
Go
package http
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"time"
|
|
)
|
|
|
|
type (
|
|
BaseResponse interface {
|
|
IsSuccess() bool
|
|
SentAt() time.Time
|
|
Copy(w io.Writer) error
|
|
}
|
|
Response struct {
|
|
status uint16
|
|
timestamp time.Time
|
|
}
|
|
|
|
Message struct {
|
|
Response
|
|
message string
|
|
}
|
|
|
|
Object struct {
|
|
Response
|
|
data any
|
|
}
|
|
)
|
|
|
|
func MakeResponse(status uint16) Response {
|
|
return Response{
|
|
status: status,
|
|
timestamp: time.Now(),
|
|
}
|
|
}
|
|
|
|
func MakeMessage(status uint16, message string) Message {
|
|
r := MakeResponse(status)
|
|
return Message{
|
|
Response: r,
|
|
message: message,
|
|
}
|
|
}
|
|
|
|
func MakeObject(status uint16, data any) Object {
|
|
r := MakeResponse(status)
|
|
return Object{
|
|
Response: r,
|
|
data: data,
|
|
}
|
|
}
|
|
|
|
func (r Response) IsSuccess() bool {
|
|
return r.status >= 200 && r.status < 300
|
|
}
|
|
|
|
func (r Response) SentAt() time.Time {
|
|
return r.timestamp
|
|
}
|
|
|
|
func (r Response) Copy(w io.Writer) error {
|
|
encoder := json.NewEncoder(w)
|
|
err := encoder.Encode(r)
|
|
return err
|
|
}
|
|
|
|
func (r Response) MarshalJSON() ([]byte, error) {
|
|
return json.Marshal(r.toMap())
|
|
}
|
|
|
|
func (r Response) toMap() map[string]any {
|
|
return map[string]any{
|
|
"status": r.status,
|
|
"timestamp": r.timestamp,
|
|
}
|
|
}
|
|
|
|
func (m Message) Copy(w io.Writer) error {
|
|
encoder := json.NewEncoder(w)
|
|
err := encoder.Encode(m)
|
|
return err
|
|
}
|
|
|
|
func (m Message) MarshalJSON() ([]byte, error) {
|
|
mp := m.toMap()
|
|
mp["message"] = m.message
|
|
return json.Marshal(mp)
|
|
}
|
|
|
|
func (o Object) Copy(w io.Writer) error {
|
|
encoder := json.NewEncoder(w)
|
|
err := encoder.Encode(o)
|
|
return err
|
|
}
|
|
|
|
func (o Object) MarshalJSON() ([]byte, error) {
|
|
mp := o.toMap()
|
|
mp["data"] = o.data
|
|
return json.Marshal(mp)
|
|
}
|