65 lines
1.2 KiB
Go
65 lines
1.2 KiB
Go
package http
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"source.toby3d.me/toby3d/auth/internal/common"
|
|
)
|
|
|
|
type (
|
|
Response struct {
|
|
CheckedAt *DateTime `json:"checkedAt"`
|
|
Ok bool `json:"ok"`
|
|
}
|
|
|
|
DateTime struct {
|
|
time.Time `json:"-"`
|
|
}
|
|
|
|
Handler struct {
|
|
// Use fixed timestamp in response instead of [time.Now].
|
|
Test bool
|
|
}
|
|
)
|
|
|
|
func NewHandler() *Handler {
|
|
return new(Handler)
|
|
}
|
|
|
|
// getCurrentDateTime returns incoming request timestamp or fixed datetime for
|
|
// tests.
|
|
func (h Handler) getCurrentDateTime() time.Time {
|
|
if h.Test {
|
|
return time.Unix(common.TestUnix, 0).UTC()
|
|
}
|
|
|
|
return time.Now().UTC()
|
|
}
|
|
|
|
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set(common.HeaderContentType, common.MIMEApplicationJSONCharsetUTF8)
|
|
_ = json.NewEncoder(w).Encode(NewResponse(h.getCurrentDateTime(), true))
|
|
}
|
|
|
|
func NewResponse(checkedAt time.Time, ok bool) *Response {
|
|
return &Response{
|
|
Ok: ok,
|
|
CheckedAt: NewDateTime(checkedAt),
|
|
}
|
|
}
|
|
|
|
func NewDateTime(ts time.Time) *DateTime {
|
|
return &DateTime{Time: ts}
|
|
}
|
|
|
|
func (dt DateTime) MarshalJSON() ([]byte, error) {
|
|
if dt.Time.IsZero() {
|
|
return nil, nil
|
|
}
|
|
|
|
return []byte(strconv.Quote(dt.Time.Format(time.RFC3339))), nil
|
|
}
|