chore: import lab3 baseline
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/postgres"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/session"
|
||||
)
|
||||
|
||||
func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodPost {
|
||||
return methodNotAllowed(w, http.MethodPost)
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 1))
|
||||
if err != nil || len(body) != 0 {
|
||||
return invalidRequest()
|
||||
}
|
||||
username, passwordValue, ok := singleBasicAuth(r)
|
||||
if !ok {
|
||||
return unauthorized()
|
||||
}
|
||||
credentials, err := s.messengerStore.UserByUsername(r.Context(), username)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
if _, verifyErr := s.passwords.Verify(passwordValue, s.passwords.DummyHash()); verifyErr != nil {
|
||||
return internalError()
|
||||
}
|
||||
return unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
verified, err := s.passwords.Verify(passwordValue, credentials.PasswordHash)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
}
|
||||
if !verified {
|
||||
return unauthorized()
|
||||
}
|
||||
token, expiresAt, err := s.sessions.Create(r.Context(), credentials.ID, s.sessionTTL)
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User User `json:"user"`
|
||||
}{token, "Bearer", model.FormatTime(expiresAt), credentials.User})
|
||||
return nil
|
||||
}
|
||||
|
||||
func singleBasicAuth(r *http.Request) (string, string, bool) {
|
||||
if len(r.Header.Values("Authorization")) != 1 {
|
||||
return "", "", false
|
||||
}
|
||||
username, passwordValue, ok := r.BasicAuth()
|
||||
return username, passwordValue, ok && username != ""
|
||||
}
|
||||
|
||||
func (s *Server) revokeSession(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodDelete {
|
||||
return methodNotAllowed(w, http.MethodDelete)
|
||||
}
|
||||
_, token, authErr := s.authenticate(r)
|
||||
if authErr != nil {
|
||||
return authErr
|
||||
}
|
||||
if err := s.sessions.Delete(r.Context(), token); errors.Is(err, session.ErrNotFound) {
|
||||
return unauthorized()
|
||||
} else if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) authenticate(r *http.Request) (User, string, *apiError) {
|
||||
values := r.Header.Values("Authorization")
|
||||
if len(values) != 1 {
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
scheme, token, found := strings.Cut(values[0], " ")
|
||||
if !found || !strings.EqualFold(scheme, "Bearer") || token == "" || strings.ContainsAny(token, " \t\r\n") {
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
userID, err := s.sessions.UserID(r.Context(), token)
|
||||
if errors.Is(err, session.ErrNotFound) || errors.Is(err, session.ErrInvalidToken) {
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, "", unavailable()
|
||||
}
|
||||
user, err := s.messengerStore.UserByID(r.Context(), userID)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
_ = s.sessions.Delete(r.Context(), token)
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, "", unavailable()
|
||||
}
|
||||
return user, token, nil
|
||||
}
|
||||
|
||||
func authenticationChallenge(r *http.Request) string {
|
||||
if r.URL.Path == "/api/v1/auth/sessions" {
|
||||
return `Basic realm="messenger", charset="UTF-8"`
|
||||
}
|
||||
return `Bearer realm="messenger"`
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
const (
|
||||
errorCodeInvalidRequest = "invalid_request"
|
||||
errorCodeUnauthorized = "unauthorized"
|
||||
errorCodeNotFound = "not_found"
|
||||
errorCodeInternal = "internal_error"
|
||||
errorCodeUnsupportedMediaType = "unsupported_media_type"
|
||||
errorCodePayloadTooLarge = "payload_too_large"
|
||||
errorCodeUnavailable = "unavailable"
|
||||
errorCodeConflict = "conflict"
|
||||
)
|
||||
|
||||
type apiError struct {
|
||||
status int
|
||||
code string
|
||||
message string
|
||||
}
|
||||
|
||||
func methodNotAllowed(w http.ResponseWriter, allowed string) *apiError {
|
||||
w.Header().Set("Allow", allowed)
|
||||
return &apiError{http.StatusMethodNotAllowed, errorCodeInvalidRequest, "method not allowed"}
|
||||
}
|
||||
|
||||
func invalidRequest() *apiError {
|
||||
return &apiError{http.StatusBadRequest, errorCodeInvalidRequest, "invalid request"}
|
||||
}
|
||||
|
||||
func unauthorized() *apiError {
|
||||
return &apiError{http.StatusUnauthorized, errorCodeUnauthorized, "authentication required"}
|
||||
}
|
||||
|
||||
func notFound() *apiError {
|
||||
return &apiError{http.StatusNotFound, errorCodeNotFound, "resource not found"}
|
||||
}
|
||||
|
||||
func internalError() *apiError {
|
||||
return &apiError{http.StatusInternalServerError, errorCodeInternal, "internal server error"}
|
||||
}
|
||||
|
||||
func unavailable() *apiError {
|
||||
return &apiError{http.StatusServiceUnavailable, errorCodeUnavailable, "service unavailable"}
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, requestID string, err *apiError) {
|
||||
writeJSON(w, err.status, map[string]any{"error": map[string]string{
|
||||
"code": err.code, "message": err.message, "request_id": requestID,
|
||||
}})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/postgres"
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
func (s *Server) live(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) readiness(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet)
|
||||
}
|
||||
if !s.ready.Load() {
|
||||
return unavailable()
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
if err := s.messengerStore.Ping(ctx); err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if err := s.sessions.Ping(ctx); err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) users(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodPost {
|
||||
return methodNotAllowed(w, http.MethodPost)
|
||||
}
|
||||
var input struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := readJSON(w, r, &input); err != nil {
|
||||
return err
|
||||
}
|
||||
if !usernamePattern.MatchString(input.Username) || !validText(input.DisplayName, 100) || !validPassword(input.Password) {
|
||||
return invalidRequest()
|
||||
}
|
||||
passwordHash, err := s.passwords.Hash(input.Password)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
}
|
||||
user, err := s.messengerStore.CreateUser(r.Context(), input.Username, input.DisplayName, passwordHash)
|
||||
if errors.Is(err, postgres.ErrConflict) {
|
||||
return &apiError{http.StatusConflict, errorCodeConflict, "username already exists"}
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, user)
|
||||
return nil
|
||||
}
|
||||
|
||||
func validPassword(value string) bool {
|
||||
length := utf8.RuneCountInString(value)
|
||||
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && length >= 12 && length <= 128
|
||||
}
|
||||
|
||||
func (s *Server) me(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet)
|
||||
}
|
||||
user, _, err := s.authenticate(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
writeJSON(w, http.StatusOK, user)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) chats(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodPost && r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet+", "+http.MethodPost)
|
||||
}
|
||||
user, _, authErr := s.authenticate(r)
|
||||
if authErr != nil {
|
||||
return authErr
|
||||
}
|
||||
if r.Method == http.MethodGet {
|
||||
return s.listChats(w, r, user)
|
||||
}
|
||||
var input struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
if err := readJSON(w, r, &input); err != nil {
|
||||
return err
|
||||
}
|
||||
if !validText(input.Title, 100) || len(input.MemberIDs) < 1 || len(input.MemberIDs) > 100 {
|
||||
return invalidRequest()
|
||||
}
|
||||
members := make(map[string]struct{}, len(input.MemberIDs))
|
||||
for i, memberID := range input.MemberIDs {
|
||||
canonical, valid := canonicalID(memberID)
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
if _, duplicate := members[canonical]; duplicate {
|
||||
return invalidRequest()
|
||||
}
|
||||
members[canonical] = struct{}{}
|
||||
input.MemberIDs[i] = canonical
|
||||
}
|
||||
if _, included := members[user.ID]; !included {
|
||||
return invalidRequest()
|
||||
}
|
||||
chat, err := s.messengerStore.CreateChat(r.Context(), input.Title, input.MemberIDs, user.ID)
|
||||
if errors.Is(err, postgres.ErrInvalidMembers) {
|
||||
return invalidRequest()
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, chat)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) listChats(w http.ResponseWriter, r *http.Request, user User) *apiError {
|
||||
limit, cursor, err := pageParams(r, "chat", user.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items, hasNext, listErr := s.messengerStore.ListChats(r.Context(), user.ID, cursorPosition(cursor), limit)
|
||||
if errors.Is(listErr, postgres.ErrInvalidCursor) {
|
||||
return invalidRequest()
|
||||
}
|
||||
if listErr != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if items == nil {
|
||||
items = []Chat{}
|
||||
}
|
||||
var next *string
|
||||
if hasNext {
|
||||
last := items[len(items)-1]
|
||||
value := encodeCursor("chat", user.ID, last.CreatedAt, last.ID)
|
||||
next = &value
|
||||
}
|
||||
writeJSON(w, http.StatusOK, struct {
|
||||
Items []Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}{items, next})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) chat(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet)
|
||||
}
|
||||
user, _, authErr := s.authenticate(r)
|
||||
if authErr != nil {
|
||||
return authErr
|
||||
}
|
||||
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
chat, err := s.messengerStore.ChatForUser(r.Context(), chatID, user.ID)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusOK, chat)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodPost && r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet+", "+http.MethodPost)
|
||||
}
|
||||
user, _, authErr := s.authenticate(r)
|
||||
if authErr != nil {
|
||||
return authErr
|
||||
}
|
||||
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
if r.Method == http.MethodGet {
|
||||
return s.listMessages(w, r, user, chatID)
|
||||
}
|
||||
key, valid := idempotencyKey(r)
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
var input struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if err := readJSON(w, r, &input); err != nil {
|
||||
return err
|
||||
}
|
||||
if !validText(input.Text, 4000) {
|
||||
return invalidRequest()
|
||||
}
|
||||
message, replay, err := s.messengerStore.CreateMessage(
|
||||
r.Context(), chatID, user.ID, input.Text, key, s.idempotencyTTL,
|
||||
)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
if errors.Is(err, postgres.ErrIdempotencyConflict) {
|
||||
return &apiError{http.StatusConflict, errorCodeConflict, "idempotency key conflicts with previous request"}
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if replay {
|
||||
s.metrics.replays.Inc()
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, message)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, user User, chatID string) *apiError {
|
||||
limit, cursor, err := pageParams(r, "message", chatID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items, hasNext, listErr := s.messengerStore.ListMessages(r.Context(), chatID, user.ID, cursorPosition(cursor), limit)
|
||||
if errors.Is(listErr, postgres.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
if errors.Is(listErr, postgres.ErrInvalidCursor) {
|
||||
return invalidRequest()
|
||||
}
|
||||
if listErr != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if items == nil {
|
||||
items = []Message{}
|
||||
}
|
||||
var next *string
|
||||
if hasNext {
|
||||
last := items[len(items)-1]
|
||||
value := encodeCursor("message", chatID, last.CreatedAt, last.ID)
|
||||
next = &value
|
||||
}
|
||||
writeJSON(w, http.StatusOK, struct {
|
||||
Items []Message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}{items, next})
|
||||
return nil
|
||||
}
|
||||
|
||||
func cursorPosition(cursor *pageCursor) *model.Position {
|
||||
if cursor == nil {
|
||||
return nil
|
||||
}
|
||||
return &model.Position{CreatedAt: cursor.Time, ID: cursor.ID}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||
)
|
||||
|
||||
type MessengerStore interface {
|
||||
Ping(context.Context) error
|
||||
CreateUser(context.Context, string, string, string) (model.User, error)
|
||||
UserByID(context.Context, string) (model.User, error)
|
||||
UserByUsername(context.Context, string) (model.UserCredentials, error)
|
||||
CreateChat(context.Context, string, []string, string) (model.Chat, error)
|
||||
ChatForUser(context.Context, string, string) (model.Chat, error)
|
||||
ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error)
|
||||
CreateMessage(context.Context, string, string, string, string, time.Duration) (model.Message, bool, error)
|
||||
ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error)
|
||||
}
|
||||
|
||||
type SessionStore interface {
|
||||
Ping(context.Context) error
|
||||
Create(context.Context, string, time.Duration) (string, time.Time, error)
|
||||
UserID(context.Context, string) (string, error)
|
||||
Delete(context.Context, string) error
|
||||
}
|
||||
|
||||
type PasswordService interface {
|
||||
Hash(string) (string, error)
|
||||
Verify(string, string) (bool, error)
|
||||
DummyHash() string
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/collectors"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
)
|
||||
|
||||
type metrics struct {
|
||||
requests *prometheus.CounterVec
|
||||
duration *prometheus.HistogramVec
|
||||
inFlight prometheus.Gauge
|
||||
replays prometheus.Counter
|
||||
handler http.Handler
|
||||
}
|
||||
|
||||
func newMetrics() *metrics {
|
||||
registry := prometheus.NewRegistry()
|
||||
result := &metrics{
|
||||
requests: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: "messenger",
|
||||
Subsystem: "http",
|
||||
Name: "requests_total",
|
||||
Help: "Completed HTTP requests.",
|
||||
}, []string{"method", "route", "status_class"}),
|
||||
duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Namespace: "messenger",
|
||||
Subsystem: "http",
|
||||
Name: "request_duration_seconds",
|
||||
Help: "HTTP request duration in seconds.",
|
||||
Buckets: prometheus.DefBuckets,
|
||||
}, []string{"method", "route"}),
|
||||
inFlight: prometheus.NewGauge(prometheus.GaugeOpts{
|
||||
Namespace: "messenger",
|
||||
Subsystem: "http",
|
||||
Name: "requests_in_flight",
|
||||
Help: "HTTP requests currently being served.",
|
||||
}),
|
||||
replays: prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Namespace: "messenger",
|
||||
Subsystem: "http",
|
||||
Name: "idempotency_replays_total",
|
||||
Help: "Message requests served from an idempotency record.",
|
||||
}),
|
||||
}
|
||||
registry.MustRegister(
|
||||
result.requests,
|
||||
result.duration,
|
||||
result.inFlight,
|
||||
result.replays,
|
||||
collectors.NewGoCollector(),
|
||||
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
|
||||
)
|
||||
result.handler = promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
|
||||
return result
|
||||
}
|
||||
|
||||
func (m *metrics) observe(r *http.Request, status int, started time.Time) {
|
||||
route := routeTemplate(r.URL.Path)
|
||||
m.requests.WithLabelValues(r.Method, route, strconv.Itoa(status/100)+"xx").Inc()
|
||||
m.duration.WithLabelValues(r.Method, route).Observe(time.Since(started).Seconds())
|
||||
}
|
||||
|
||||
func routeTemplate(path string) string {
|
||||
switch path {
|
||||
case "/health/live", "/health/ready", "/metrics", "/api/v1/users", "/api/v1/users/me",
|
||||
"/api/v1/auth/sessions", "/api/v1/auth/sessions/current", "/api/v1/chats":
|
||||
return path
|
||||
}
|
||||
parts := strings.Split(strings.Trim(path, "/"), "/")
|
||||
if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" {
|
||||
return "/api/v1/chats/{chat_id}"
|
||||
}
|
||||
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "messages" {
|
||||
return "/api/v1/chats/{chat_id}/messages"
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type User = model.User
|
||||
type Chat = model.Chat
|
||||
type Message = model.Message
|
||||
|
||||
func newID() (string, error) {
|
||||
id, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id.String(), nil
|
||||
}
|
||||
|
||||
func canonicalID(value string) (string, bool) {
|
||||
if len(value) != 36 {
|
||||
return "", false
|
||||
}
|
||||
id, err := uuid.Parse(value)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
return id.String(), true
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const maxRequestBytes = 1 << 20
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func readJSON(w http.ResponseWriter, r *http.Request, target any) *apiError {
|
||||
mediaType, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || mediaType != "application/json" || (params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
|
||||
return &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "expected application/json"}
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxRequestBytes)
|
||||
data, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
var tooLarge *http.MaxBytesError
|
||||
if errors.As(err, &tooLarge) {
|
||||
return &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "request body too large"}
|
||||
}
|
||||
return invalidRequest()
|
||||
}
|
||||
if !utf8.Valid(data) {
|
||||
return invalidRequest()
|
||||
}
|
||||
var object map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &object); err != nil || object == nil {
|
||||
return invalidRequest()
|
||||
}
|
||||
normalized, err := json.Marshal(object)
|
||||
if err != nil {
|
||||
return invalidRequest()
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(normalized))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
return invalidRequest()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validText(value string, maxRunes int) bool {
|
||||
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= maxRunes
|
||||
}
|
||||
|
||||
func idempotencyKey(r *http.Request) (string, bool) {
|
||||
values := r.Header.Values("Idempotency-Key")
|
||||
if len(values) != 1 || !idempotencyKeyPattern.MatchString(values[0]) {
|
||||
return "", false
|
||||
}
|
||||
return values[0], true
|
||||
}
|
||||
|
||||
type pageCursor struct {
|
||||
Kind string `json:"kind"`
|
||||
Resource string `json:"resource"`
|
||||
Time time.Time `json:"time"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
func pageParams(r *http.Request, kind, resource string) (int, *pageCursor, *apiError) {
|
||||
query, err := url.ParseQuery(r.URL.RawQuery)
|
||||
if err != nil {
|
||||
return 0, nil, invalidRequest()
|
||||
}
|
||||
for key := range query {
|
||||
if key != "limit" && key != "cursor" {
|
||||
return 0, nil, invalidRequest()
|
||||
}
|
||||
if len(query[key]) != 1 {
|
||||
return 0, nil, invalidRequest()
|
||||
}
|
||||
}
|
||||
limit := 50
|
||||
if value, present := query["limit"]; present {
|
||||
parsed, err := strconv.Atoi(value[0])
|
||||
if err != nil || parsed < 1 || parsed > 100 {
|
||||
return 0, nil, invalidRequest()
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
if value, present := query["cursor"]; present {
|
||||
cursor, valid := decodeCursor(value[0], kind, resource)
|
||||
if !valid {
|
||||
return 0, nil, invalidRequest()
|
||||
}
|
||||
return limit, cursor, nil
|
||||
}
|
||||
return limit, nil, nil
|
||||
}
|
||||
|
||||
func encodeCursor(kind, resource string, createdAt time.Time, id string) string {
|
||||
data, _ := json.Marshal(pageCursor{kind, resource, createdAt, id})
|
||||
return base64.RawURLEncoding.EncodeToString(data)
|
||||
}
|
||||
|
||||
func decodeCursor(value, kind, resource string) (*pageCursor, bool) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(value)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
var cursor pageCursor
|
||||
if err := json.Unmarshal(data, &cursor); err != nil || cursor.Kind != kind || cursor.Resource != resource {
|
||||
return nil, false
|
||||
}
|
||||
if cursor.Time.IsZero() {
|
||||
return nil, false
|
||||
}
|
||||
if _, valid := canonicalID(cursor.ID); !valid {
|
||||
return nil, false
|
||||
}
|
||||
return &cursor, true
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type requestHandler func(http.ResponseWriter, *http.Request) *apiError
|
||||
|
||||
func (s *Server) route(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
var handler requestHandler
|
||||
switch r.URL.Path {
|
||||
case "/health/live":
|
||||
handler = s.live
|
||||
case "/health/ready":
|
||||
handler = s.readiness
|
||||
case "/metrics":
|
||||
s.metrics.handler.ServeHTTP(w, r)
|
||||
return nil
|
||||
case "/api/v1/users":
|
||||
handler = s.users
|
||||
case "/api/v1/users/me":
|
||||
handler = s.me
|
||||
case "/api/v1/auth/sessions":
|
||||
handler = s.createSession
|
||||
case "/api/v1/auth/sessions/current":
|
||||
handler = s.revokeSession
|
||||
case "/api/v1/chats":
|
||||
handler = s.chats
|
||||
default:
|
||||
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
|
||||
if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" {
|
||||
handler = s.chat
|
||||
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "messages" {
|
||||
handler = s.messages
|
||||
} else {
|
||||
return notFound()
|
||||
}
|
||||
}
|
||||
return handler(w, r)
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
messengerStore MessengerStore
|
||||
sessions SessionStore
|
||||
passwords PasswordService
|
||||
sessionTTL time.Duration
|
||||
idempotencyTTL time.Duration
|
||||
requestTTL time.Duration
|
||||
instanceID string
|
||||
logger *slog.Logger
|
||||
swaggerPort string
|
||||
metrics *metrics
|
||||
ready atomic.Bool
|
||||
}
|
||||
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (w *statusWriter) WriteHeader(status int) {
|
||||
w.status = status
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func NewServer(
|
||||
logger *slog.Logger,
|
||||
messages MessengerStore,
|
||||
sessions SessionStore,
|
||||
passwords PasswordService,
|
||||
sessionTTL time.Duration,
|
||||
idempotencyTTL time.Duration,
|
||||
requestTTL time.Duration,
|
||||
instanceID string,
|
||||
swaggerPort string,
|
||||
) *Server {
|
||||
s := &Server{
|
||||
messengerStore: messages, sessions: sessions, passwords: passwords,
|
||||
sessionTTL: sessionTTL, idempotencyTTL: idempotencyTTL, requestTTL: requestTTL,
|
||||
instanceID: instanceID, logger: logger, swaggerPort: swaggerPort, metrics: newMetrics(),
|
||||
}
|
||||
s.ready.Store(true)
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) SetReady(ready bool) {
|
||||
s.ready.Store(ready)
|
||||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
return http.HandlerFunc(s.serve)
|
||||
}
|
||||
|
||||
func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", s.instanceID)
|
||||
requestID, err := newID()
|
||||
if err != nil {
|
||||
http.Error(w, "server unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
wrapped := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
started := time.Now()
|
||||
s.metrics.inFlight.Inc()
|
||||
defer func() {
|
||||
s.metrics.inFlight.Dec()
|
||||
if recovered := recover(); recovered != nil {
|
||||
s.logger.Error("request panic", "request_id", requestID, "method", r.Method, "path", r.URL.Path)
|
||||
if wrapped.status == http.StatusOK {
|
||||
writeError(wrapped, requestID, internalError())
|
||||
}
|
||||
}
|
||||
s.metrics.observe(r, wrapped.status, started)
|
||||
s.logger.Info("request", "request_id", requestID, "method", r.Method, "path", r.URL.Path, "status", wrapped.status, "duration_ms", time.Since(started).Milliseconds())
|
||||
}()
|
||||
if s.allowSwaggerOrigin(wrapped, r) && r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
|
||||
wrapped.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
|
||||
wrapped.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, Idempotency-Key")
|
||||
wrapped.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), s.requestTTL)
|
||||
defer cancel()
|
||||
r = r.WithContext(ctx)
|
||||
if apiErr := s.route(wrapped, r); apiErr != nil {
|
||||
if apiErr.status == http.StatusUnauthorized {
|
||||
wrapped.Header().Set("WWW-Authenticate", authenticationChallenge(r))
|
||||
}
|
||||
writeError(wrapped, requestID, apiErr)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) allowSwaggerOrigin(w http.ResponseWriter, r *http.Request) bool {
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin != "http://localhost:"+s.swaggerPort && origin != "http://127.0.0.1:"+s.swaggerPort {
|
||||
return false
|
||||
}
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
w.Header().Set("Access-Control-Expose-Headers", "X-Request-Id, X-Instance-Id")
|
||||
w.Header().Add("Vary", "Origin")
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/postgres"
|
||||
)
|
||||
|
||||
var errDependency = errors.New("dependency unavailable")
|
||||
|
||||
type MessengerSuite struct {
|
||||
suite.Suite
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func TestMessengerSuite(t *testing.T) {
|
||||
suite.Run(t, new(MessengerSuite))
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) SetupTest() {
|
||||
s.logger = slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
}
|
||||
|
||||
type messengerStoreStub struct {
|
||||
pingErr error
|
||||
userByID model.User
|
||||
userByIDErr error
|
||||
credentials model.UserCredentials
|
||||
credentialsErr error
|
||||
message model.Message
|
||||
messageReplay bool
|
||||
messageErr error
|
||||
}
|
||||
|
||||
func (s messengerStoreStub) Ping(context.Context) error { return s.pingErr }
|
||||
func (messengerStoreStub) CreateUser(context.Context, string, string, string) (model.User, error) {
|
||||
return model.User{}, nil
|
||||
}
|
||||
func (s messengerStoreStub) UserByID(context.Context, string) (model.User, error) {
|
||||
return s.userByID, s.userByIDErr
|
||||
}
|
||||
func (s messengerStoreStub) UserByUsername(context.Context, string) (model.UserCredentials, error) {
|
||||
return s.credentials, s.credentialsErr
|
||||
}
|
||||
func (messengerStoreStub) CreateChat(context.Context, string, []string, string) (model.Chat, error) {
|
||||
return model.Chat{}, nil
|
||||
}
|
||||
func (messengerStoreStub) ChatForUser(context.Context, string, string) (model.Chat, error) {
|
||||
return model.Chat{}, nil
|
||||
}
|
||||
func (messengerStoreStub) ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error) {
|
||||
return nil, false, nil
|
||||
}
|
||||
func (s messengerStoreStub) CreateMessage(context.Context, string, string, string, string, time.Duration) (model.Message, bool, error) {
|
||||
return s.message, s.messageReplay, s.messageErr
|
||||
}
|
||||
func (messengerStoreStub) ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error) {
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
type sessionStub struct {
|
||||
pingErr error
|
||||
userID string
|
||||
userIDErr error
|
||||
}
|
||||
|
||||
func (s sessionStub) Ping(context.Context) error { return s.pingErr }
|
||||
func (sessionStub) Create(context.Context, string, time.Duration) (string, time.Time, error) {
|
||||
return "token", time.Now().Add(time.Hour), nil
|
||||
}
|
||||
func (s sessionStub) UserID(context.Context, string) (string, error) { return s.userID, s.userIDErr }
|
||||
func (sessionStub) Delete(context.Context, string) error { return nil }
|
||||
|
||||
type passwordsStub struct {
|
||||
verified bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (passwordsStub) Hash(string) (string, error) { return "hash", nil }
|
||||
func (passwordsStub) DummyHash() string { return "hash" }
|
||||
func (s passwordsStub) Verify(string, string) (bool, error) {
|
||||
return s.verified, s.err
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestReadinessReturnsUnavailableForDependencyFailure() {
|
||||
t := s.T()
|
||||
tests := []struct {
|
||||
name string
|
||||
store messengerStoreStub
|
||||
sessions sessionStub
|
||||
}{
|
||||
{name: "postgres", store: messengerStoreStub{pingErr: errDependency}},
|
||||
{name: "valkey", sessions: sessionStub{pingErr: errDependency}},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := s.newTestServer(tt.store, tt.sessions, passwordsStub{})
|
||||
response := serveRequest(server, http.MethodGet, "/health/ready", "")
|
||||
if response.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestBusinessRequestReturnsUnavailableForDependencyFailure() {
|
||||
t := s.T()
|
||||
tests := []struct {
|
||||
name string
|
||||
store messengerStoreStub
|
||||
sessions sessionStub
|
||||
}{
|
||||
{name: "valkey", sessions: sessionStub{userIDErr: errDependency}},
|
||||
{name: "postgres", store: messengerStoreStub{userByIDErr: errDependency}, sessions: sessionStub{userID: "user-id"}},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := s.newTestServer(tt.store, tt.sessions, passwordsStub{})
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
||||
request.Header.Set("Authorization", "Bearer valid-token")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestAuthenticationChallenges() {
|
||||
t := s.T()
|
||||
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
|
||||
bearer := serveRequest(server, http.MethodGet, "/api/v1/users/me", "")
|
||||
if bearer.Code != http.StatusUnauthorized || bearer.Header().Get("WWW-Authenticate") != `Bearer realm="messenger"` {
|
||||
t.Fatalf("business challenge = %d %q", bearer.Code, bearer.Header().Get("WWW-Authenticate"))
|
||||
}
|
||||
|
||||
store := messengerStoreStub{credentials: model.UserCredentials{PasswordHash: "hash"}}
|
||||
server = s.newTestServer(store, sessionStub{}, passwordsStub{verified: false})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
request.SetBasicAuth("user", "wrong-password")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusUnauthorized || response.Header().Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
|
||||
t.Fatalf("session challenge = %d %q", response.Code, response.Header().Get("WWW-Authenticate"))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestSessionCreationRejectsChunkedBody() {
|
||||
t := s.T()
|
||||
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}"))
|
||||
request.ContentLength = -1
|
||||
request.SetBasicAuth("user", "password")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestRegistrationRejectsWhitespacePassword() {
|
||||
t := s.T()
|
||||
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
|
||||
response := serveRequest(server, http.MethodPost, "/api/v1/users", `{"username":"student","display_name":"Student","password":" "}`)
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestInstanceHeaderIsSetOnSuccessAndError() {
|
||||
t := s.T()
|
||||
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
|
||||
for _, response := range []*httptest.ResponseRecorder{
|
||||
serveRequest(server, http.MethodGet, "/health/live", ""),
|
||||
serveRequest(server, http.MethodGet, "/api/v1/users/me", ""),
|
||||
} {
|
||||
if value := response.Header().Get("X-Instance-Id"); value != "test-instance" {
|
||||
t.Fatalf("X-Instance-Id = %q, want test-instance", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestMessageCreationValidatesIdempotencyKey() {
|
||||
t := s.T()
|
||||
store := messengerStoreStub{userByID: model.User{ID: "user-id"}}
|
||||
server := s.newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{})
|
||||
tests := []struct {
|
||||
name string
|
||||
key string
|
||||
}{
|
||||
{name: "missing"},
|
||||
{name: "invalid", key: "invalid key"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/chats/00000000-0000-0000-0000-000000000001/messages", strings.NewReader(`{"text":"message"}`))
|
||||
request.Header.Set("Authorization", "Bearer valid-token")
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
if tt.key != "" {
|
||||
request.Header.Set("Idempotency-Key", tt.key)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestMessageCreationReturnsConflictForReusedKeyWithDifferentBody() {
|
||||
t := s.T()
|
||||
store := messengerStoreStub{
|
||||
userByID: model.User{ID: "user-id"},
|
||||
messageErr: fmt.Errorf("create message: %w", postgres.ErrIdempotencyConflict),
|
||||
}
|
||||
server := s.newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/chats/00000000-0000-0000-0000-000000000001/messages", strings.NewReader(`{"text":"different"}`))
|
||||
request.Header.Set("Authorization", "Bearer valid-token")
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("Idempotency-Key", "same-key")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusConflict)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) newTestServer(messages MessengerStore, sessions SessionStore, passwords PasswordService) *Server {
|
||||
return NewServer(s.logger, messages, sessions, passwords, time.Hour, 24*time.Hour, time.Second, "test-instance", "8081")
|
||||
}
|
||||
|
||||
func serveRequest(server *Server, method, path, body string) *httptest.ResponseRecorder {
|
||||
request := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if body != "" {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
return response
|
||||
}
|
||||
Reference in New Issue
Block a user