Implement lab 3 level 4 failover and idempotency
This commit is contained in:
@@ -0,0 +1,190 @@
|
||||
package httputils
|
||||
|
||||
import (
|
||||
"encoding/json/v2"
|
||||
"errors"
|
||||
"highload/internal/service"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type ErrorResponse struct {
|
||||
Error ErrorDetails `json:"error"`
|
||||
}
|
||||
|
||||
type ErrorDetails struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
func Decode[T any](r *http.Request) (*T, int) {
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
|
||||
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||
|
||||
if err != nil || mediaType != "application/json" {
|
||||
return nil, http.StatusUnsupportedMediaType
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return nil, http.StatusBadRequest
|
||||
}
|
||||
|
||||
if !utf8.Valid(body) {
|
||||
return nil, http.StatusBadRequest
|
||||
}
|
||||
|
||||
req := new(T)
|
||||
|
||||
err = json.Unmarshal(body, req, json.RejectUnknownMembers(true))
|
||||
if err != nil {
|
||||
return nil, http.StatusBadRequest
|
||||
}
|
||||
return req, http.StatusOK
|
||||
|
||||
}
|
||||
|
||||
func GetLimitAndCursor(r *http.Request) (limit *int, cursor *string, ok bool) {
|
||||
query := r.URL.Query()
|
||||
|
||||
var currentLimit *int
|
||||
|
||||
if query.Has("limit") {
|
||||
limitStr := query.Get("limit")
|
||||
|
||||
if limitStr == "" {
|
||||
return nil, nil, false
|
||||
}
|
||||
limitInt, err := strconv.Atoi(limitStr)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
currentLimit = &limitInt
|
||||
|
||||
}
|
||||
|
||||
var currentCursor *string
|
||||
if query.Has("cursor") {
|
||||
cursor := query.Get("cursor")
|
||||
currentCursor = &cursor
|
||||
}
|
||||
|
||||
return currentLimit, currentCursor, true
|
||||
}
|
||||
|
||||
func WriteJSON[T any](w http.ResponseWriter, status int, response T) error {
|
||||
data, err := json.Marshal(response)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_, err = w.Write(data)
|
||||
return err
|
||||
}
|
||||
|
||||
func ErrorFromService(err error) (int, string) {
|
||||
|
||||
switch {
|
||||
case errors.Is(err, service.ErrInvalidInput):
|
||||
return http.StatusBadRequest, "invalid_request"
|
||||
|
||||
case errors.Is(err, service.ErrNotFound):
|
||||
return http.StatusNotFound, "not_found"
|
||||
|
||||
case errors.Is(err, service.ErrAlreadyExists):
|
||||
return http.StatusConflict, "conflict"
|
||||
case errors.Is(err, service.ErrUnauthorized):
|
||||
return http.StatusUnauthorized, "unauthorized"
|
||||
case errors.Is(err, service.ErrServiceUnavailable):
|
||||
return http.StatusServiceUnavailable, "unavailable"
|
||||
case errors.Is(err, service.ErrConflict):
|
||||
return http.StatusConflict, "conflict"
|
||||
default:
|
||||
return http.StatusInternalServerError, "internal_error"
|
||||
}
|
||||
}
|
||||
|
||||
func WriteBasicUnauthorized(w http.ResponseWriter, requestID string) error {
|
||||
w.Header().Set(
|
||||
"WWW-Authenticate",
|
||||
`Basic realm="messenger", charset="UTF-8"`,
|
||||
)
|
||||
|
||||
return WriteError(w, http.StatusUnauthorized, ErrorDetails{
|
||||
Code: "unauthorized",
|
||||
Message: "Unauthorized",
|
||||
RequestID: requestID,
|
||||
})
|
||||
}
|
||||
|
||||
func WriteBearerUnauthorized(w http.ResponseWriter, requestID string) error {
|
||||
w.Header().Set(
|
||||
"WWW-Authenticate",
|
||||
`Bearer realm="messenger"`,
|
||||
)
|
||||
|
||||
return WriteError(w, http.StatusUnauthorized, ErrorDetails{
|
||||
Code: "unauthorized",
|
||||
Message: "Unauthorized",
|
||||
RequestID: requestID,
|
||||
})
|
||||
}
|
||||
|
||||
func WriteError(w http.ResponseWriter, code int, errorDetails ErrorDetails) error {
|
||||
return WriteJSON(w, code, ErrorResponse{Error: errorDetails})
|
||||
|
||||
}
|
||||
func WriteServiceError(w http.ResponseWriter, err error, requestID string) error {
|
||||
status, code := ErrorFromService(err)
|
||||
|
||||
if status >= http.StatusInternalServerError {
|
||||
slog.Error("request failed",
|
||||
"error", err,
|
||||
"request_id", requestID,
|
||||
"status", status,
|
||||
"code", code,
|
||||
)
|
||||
}
|
||||
|
||||
return WriteJSON(w, status, ErrorResponse{
|
||||
Error: ErrorDetails{
|
||||
Code: code,
|
||||
Message: http.StatusText(status),
|
||||
RequestID: requestID,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func ExtractBearerToken(r *http.Request) (string, bool) {
|
||||
scheme, token, ok := strings.Cut(r.Header.Get("Authorization"), " ")
|
||||
if !ok ||
|
||||
!strings.EqualFold(scheme, "Bearer") ||
|
||||
token == "" ||
|
||||
strings.ContainsAny(token, " \t\r\n") {
|
||||
|
||||
return "", false
|
||||
}
|
||||
return token, true
|
||||
}
|
||||
|
||||
func FormatTime(t time.Time) string {
|
||||
return t.UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
|
||||
func CheckIdempotencyKeyPattern(key string) bool {
|
||||
patternReg := regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
return patternReg.MatchString(key)
|
||||
}
|
||||
Reference in New Issue
Block a user