mirror of
https://github.com/AdguardTeam/AdGuardHome.git
synced 2026-12-04 14:13:09 +09:00
Squashed commit of the following: commit 9324a0066202f1677bfd033d40d3a82fa9756ed9 Merge: 8a1b5cad4f9da40e39Author: Stanislav Chzhen <s.chzhen@adguard.com> Date: Thu Oct 23 17:48:01 2025 +0300 Merge branch 'master' into AGDNS-3224-aghhttp-register-slog commit 8a1b5cad4cc271ec0ecc4cb3faaba17d2bd2c767 Author: Stanislav Chzhen <s.chzhen@adguard.com> Date: Tue Oct 21 15:51:48 2025 +0300 filtering: imp code commit fe569166efb71491cdf9161b056e385d10f50204 Merge: 9a101a2f59be4ca90eAuthor: Stanislav Chzhen <s.chzhen@adguard.com> Date: Tue Oct 21 15:45:42 2025 +0300 Merge branch 'master' into AGDNS-3224-aghhttp-register-slog commit 9a101a2f5fdff4906f80be6ad1aeb6b21eca199a Author: Stanislav Chzhen <s.chzhen@adguard.com> Date: Wed Oct 15 18:52:22 2025 +0300 home: imp code commit 727e1663ba4164b39c7e8ce9a7482d660e639750 Author: Stanislav Chzhen <s.chzhen@adguard.com> Date: Wed Oct 15 10:19:56 2025 +0300 all: imp code commit 113a9017dfaa603cabc1d1743a3ac1e75ef9e92e Author: Stanislav Chzhen <s.chzhen@adguard.com> Date: Mon Oct 13 23:10:06 2025 +0300 home: fix typo commit 6588dd2dad74b46a0a58e28e7f952362d6a06044 Author: Stanislav Chzhen <s.chzhen@adguard.com> Date: Mon Oct 13 22:46:28 2025 +0300 all: imp naming commit 44278505a9479834a49d5d416bbf7d5fb751770d Author: Stanislav Chzhen <s.chzhen@adguard.com> Date: Fri Oct 10 16:20:17 2025 +0300 home: fix typo commit 7b4b57628be267b905f18f7fdd1d86472d0b4ccd Author: Stanislav Chzhen <s.chzhen@adguard.com> Date: Fri Oct 10 15:58:07 2025 +0300 all: web mw commit 93168142cb73d9e9d2bca80ef32482649828984b Author: Stanislav Chzhen <s.chzhen@adguard.com> Date: Wed Oct 8 22:20:07 2025 +0300 all: aghhttp slog commit 9155edef67f6ce7cc82e7e20361991c239066f33 Author: Stanislav Chzhen <s.chzhen@adguard.com> Date: Wed Oct 8 15:38:01 2025 +0300 aghhttp: registrar commit a3564738555a4db5e8b9f291a6484a6bc0761f34 Author: Stanislav Chzhen <s.chzhen@adguard.com> Date: Tue Oct 7 15:32:30 2025 +0300 all: http registrar
176 lines
4.3 KiB
Go
176 lines
4.3 KiB
Go
package aghhttp
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/AdguardTeam/golibs/httphdr"
|
|
"github.com/AdguardTeam/golibs/logutil/slogutil"
|
|
)
|
|
|
|
// JSON Utilities
|
|
|
|
// nsecPerMsec is the number of nanoseconds in a millisecond.
|
|
const nsecPerMsec = float64(time.Millisecond / time.Nanosecond)
|
|
|
|
// JSONDuration is a time.Duration that can be decoded from JSON and encoded
|
|
// into JSON according to our API conventions.
|
|
type JSONDuration time.Duration
|
|
|
|
// type check
|
|
var _ json.Marshaler = JSONDuration(0)
|
|
|
|
// MarshalJSON implements the json.Marshaler interface for JSONDuration. err is
|
|
// always nil.
|
|
func (d JSONDuration) MarshalJSON() (b []byte, err error) {
|
|
msec := float64(time.Duration(d)) / nsecPerMsec
|
|
b = strconv.AppendFloat(nil, msec, 'f', -1, 64)
|
|
|
|
return b, nil
|
|
}
|
|
|
|
// type check
|
|
var _ json.Unmarshaler = (*JSONDuration)(nil)
|
|
|
|
// UnmarshalJSON implements the json.Marshaler interface for *JSONDuration.
|
|
func (d *JSONDuration) UnmarshalJSON(b []byte) (err error) {
|
|
if d == nil {
|
|
return fmt.Errorf("json duration is nil")
|
|
}
|
|
|
|
msec, err := strconv.ParseFloat(string(b), 64)
|
|
if err != nil {
|
|
return fmt.Errorf("parsing json time: %w", err)
|
|
}
|
|
|
|
*d = JSONDuration(int64(msec * nsecPerMsec))
|
|
|
|
return nil
|
|
}
|
|
|
|
// 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{}
|
|
|
|
// 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', -1, 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 writes headers with the code, encodes resp into w, and logs
|
|
// any errors it encounters. r is used to get additional information from the
|
|
// request. l, w, and r must not be nil.
|
|
func WriteJSONResponse(
|
|
ctx context.Context,
|
|
l *slog.Logger,
|
|
w http.ResponseWriter,
|
|
r *http.Request,
|
|
code int,
|
|
resp any,
|
|
) {
|
|
h := w.Header()
|
|
h.Set(httphdr.ContentType, HdrValApplicationJSON)
|
|
h.Set(httphdr.Server, UserAgent())
|
|
|
|
w.WriteHeader(code)
|
|
|
|
err := json.NewEncoder(w).Encode(resp)
|
|
if err != nil {
|
|
l.ErrorContext(
|
|
ctx,
|
|
"writing json response",
|
|
"method", r.Method,
|
|
"path", r.URL.Path,
|
|
slogutil.KeyError, err,
|
|
)
|
|
}
|
|
}
|
|
|
|
// WriteJSONResponseOK writes headers with the code 200 OK, encodes v into w,
|
|
// and logs any errors it encounters. r is used to get additional information
|
|
// from the request. l, w, and r must not be nil.
|
|
func WriteJSONResponseOK(
|
|
ctx context.Context,
|
|
l *slog.Logger,
|
|
w http.ResponseWriter,
|
|
r *http.Request,
|
|
v any,
|
|
) {
|
|
WriteJSONResponse(ctx, l, w, r, http.StatusOK, v)
|
|
}
|
|
|
|
// ErrorCode is the error code as used by the HTTP API. See the ErrorCode
|
|
// definition in the OpenAPI specification.
|
|
type ErrorCode string
|
|
|
|
// ErrorCode constants.
|
|
//
|
|
// TODO(a.garipov): Expand and document codes.
|
|
const (
|
|
// ErrorCodeTMP000 is the temporary error code used for all errors.
|
|
ErrorCodeTMP000 = ""
|
|
)
|
|
|
|
// HTTPAPIErrorResp is the error response as used by the HTTP API. See the
|
|
// BadRequestResp, InternalServerErrorResp, and similar objects in the OpenAPI
|
|
// specification.
|
|
type HTTPAPIErrorResp struct {
|
|
Code ErrorCode `json:"code"`
|
|
Msg string `json:"msg"`
|
|
}
|
|
|
|
// WriteJSONResponseError encodes err as a JSON error into w, and logs any
|
|
// errors it encounters. r is used to get additional information from the
|
|
// request. l, w, and r must not be nil.
|
|
func WriteJSONResponseError(
|
|
ctx context.Context,
|
|
l *slog.Logger,
|
|
w http.ResponseWriter,
|
|
r *http.Request,
|
|
err error,
|
|
) {
|
|
l.ErrorContext(
|
|
ctx,
|
|
"writing json error",
|
|
"method", r.Method,
|
|
"path", r.URL.Path,
|
|
slogutil.KeyError, err,
|
|
)
|
|
|
|
WriteJSONResponse(ctx, l, w, r, http.StatusUnprocessableEntity, &HTTPAPIErrorResp{
|
|
Code: ErrorCodeTMP000,
|
|
Msg: err.Error(),
|
|
})
|
|
}
|