badguardhome/internal/v1/websvc/json.go
Ainar Garipov f289f4b1b6 Pull request: websvc: add system info
Merge in DNS/adguard-home from websvc-system-info to master

Squashed commit of the following:

commit 333aaa0602da254e25e0262a10080bf44a3718a7
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Thu May 12 16:32:32 2022 +0300

    websvc: fmt

commit d8a35bf71dcc59fdd595494e5b220e3d24516728
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Thu May 12 16:10:11 2022 +0300

    websvc: refactor, imp tests

commit dfeb24f3f35513bf51323d3ab6f717f582a1defc
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Wed May 11 20:52:02 2022 +0300

    websvc: add system info
2022-05-12 17:41:39 +03:00

62 lines
1.5 KiB
Go

package websvc
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"time"
"github.com/AdguardTeam/golibs/log"
)
// JSON Utilities
// jsonTime is a time.Time that can be decoded from JSON and encoded into JSON
// according to our API conventions.
type jsonTime time.Time
// type check
var _ json.Marshaler = jsonTime{}
// nsecPerMsec is the number of nanoseconds in a millisecond.
const nsecPerMsec = float64(time.Millisecond / time.Nanosecond)
// MarshalJSON implements the json.Marshaler interface for jsonTime. err is
// always nil.
func (t jsonTime) MarshalJSON() (b []byte, err error) {
msec := float64(time.Time(t).UnixNano()) / nsecPerMsec
b = strconv.AppendFloat(nil, msec, 'f', 3, 64)
return b, nil
}
// type check
var _ json.Unmarshaler = (*jsonTime)(nil)
// UnmarshalJSON implements the json.Marshaler interface for *jsonTime.
func (t *jsonTime) UnmarshalJSON(b []byte) (err error) {
if t == nil {
return fmt.Errorf("json time is nil")
}
msec, err := strconv.ParseFloat(string(b), 64)
if err != nil {
return fmt.Errorf("parsing json time: %w", err)
}
*t = jsonTime(time.Unix(0, int64(msec*nsecPerMsec)).UTC())
return nil
}
// writeJSONResponse encodes v into w and logs any errors it encounters. r is
// used to get additional information from the request.
func writeJSONResponse(w io.Writer, r *http.Request, v interface{}) {
err := json.NewEncoder(w).Encode(v)
if err != nil {
log.Error("websvc: writing resp to %s %s: %s", r.Method, r.URL.Path, err)
}
}