forked from mtusi2026/mtusi2026lab2
chore: port lab 1 solution
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"mtusi2026-messenger/internal/dto"
|
||||
)
|
||||
|
||||
func ParsePagination(w http.ResponseWriter, r *http.Request, requestID string) (limit int, cursor *string, ok bool) {
|
||||
q := r.URL.Query()
|
||||
|
||||
limit = 50
|
||||
if raw := q.Get("limit"); raw != "" {
|
||||
v, err := strconv.Atoi(raw)
|
||||
if err != nil || v < 1 || v > 100 {
|
||||
WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
dto.ErrorCodeInvalidRequest,
|
||||
"limit must be an integer between 1 and 100",
|
||||
requestID,
|
||||
)
|
||||
return 0, nil, false
|
||||
}
|
||||
limit = v
|
||||
}
|
||||
|
||||
if raw := q.Get("cursor"); raw != "" {
|
||||
cursor = &raw
|
||||
}
|
||||
|
||||
return limit, cursor, true
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"mime"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026-messenger/internal/dto"
|
||||
)
|
||||
|
||||
func DecodeJSONBody(w http.ResponseWriter, r *http.Request, requestID string, dst any) bool {
|
||||
if ct := r.Header.Get("Content-Type"); ct != "" {
|
||||
mt, _, err := mime.ParseMediaType(ct)
|
||||
if err != nil || mt != "application/json" {
|
||||
WriteError(w, http.StatusUnsupportedMediaType, dto.ErrorCodeUnsupportedMediaType, "expected application/json", requestID)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(dst); err != nil {
|
||||
WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid request body", requestID)
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026-messenger/internal/dto"
|
||||
)
|
||||
|
||||
func WriteJSON(w http.ResponseWriter, status int, body any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
}
|
||||
|
||||
func WriteError(w http.ResponseWriter, status int, code dto.ErrorCode, message, requestID string) {
|
||||
WriteJSON(w, status, dto.ErrorResponse{
|
||||
Error: dto.Error{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: requestID,
|
||||
},
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user