forked from mtusi2026/mtusi2026lab4
617 lines
18 KiB
Go
617 lines
18 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"database/sql"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"image"
|
|
_ "image/jpeg"
|
|
_ "image/png"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
|
|
_ "github.com/lib/pq"
|
|
"github.com/minio/minio-go/v7"
|
|
|
|
"mtusi2026lab3/internal/config"
|
|
"mtusi2026lab3/internal/ident"
|
|
"mtusi2026lab3/internal/password"
|
|
"mtusi2026lab3/internal/s3"
|
|
)
|
|
|
|
const (
|
|
sessionTTL = 24 * time.Hour
|
|
shutdownTimeout = 15 * time.Second
|
|
readHeaderTimeout = 5 * time.Second
|
|
idleTimeout = 60 * time.Second
|
|
instanceHeader = "X-Instance-Id"
|
|
idempotencyHeader = "Idempotency-Key"
|
|
maxIdempotencyKey = 128
|
|
maxUploadSize = 10 * 1024 * 1024
|
|
maxPixels = 40000000
|
|
)
|
|
|
|
type server struct {
|
|
db *sql.DB
|
|
instance string
|
|
s3Client *minio.Client
|
|
s3Bucket string
|
|
}
|
|
|
|
type credentials struct {
|
|
Login string `json:"login"`
|
|
Password string `json:"password"`
|
|
}
|
|
|
|
type newMessage struct {
|
|
Recipient string `json:"recipient"`
|
|
Body string `json:"body"`
|
|
AttachmentIDs []int64 `json:"attachment_ids"`
|
|
}
|
|
|
|
type message struct {
|
|
ID int64 `json:"id"`
|
|
SenderID int64 `json:"sender_id"`
|
|
Recipient string `json:"recipient"`
|
|
Body string `json:"body"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
AttachmentIDs []int64 `json:"attachment_ids"`
|
|
}
|
|
|
|
type session struct {
|
|
UserID int64
|
|
Login string
|
|
}
|
|
|
|
var errNoSession = errors.New("no valid session")
|
|
|
|
func main() {
|
|
cfg := config.Load()
|
|
|
|
db, err := sql.Open("postgres", cfg.DatabaseURL)
|
|
if err != nil {
|
|
log.Fatalf("open database: %v", err)
|
|
}
|
|
defer db.Close()
|
|
db.SetMaxOpenConns(20)
|
|
db.SetMaxIdleConns(10)
|
|
db.SetConnMaxLifetime(5 * time.Minute)
|
|
|
|
if err := db.Ping(); err != nil {
|
|
log.Fatalf("ping database: %v", err)
|
|
}
|
|
|
|
s3Client, s3Bucket, err := s3.NewClient()
|
|
if err != nil {
|
|
log.Fatalf("s3 client: %v", err)
|
|
}
|
|
|
|
ctx := context.Background()
|
|
if err := s3.EnsureBucket(ctx, s3Client, s3Bucket); err != nil {
|
|
log.Fatalf("ensure bucket: %v", err)
|
|
}
|
|
|
|
srv := &server{db: db, instance: cfg.InstanceID, s3Client: s3Client, s3Bucket: s3Bucket}
|
|
|
|
httpServer := &http.Server{
|
|
Addr: ":" + cfg.Port,
|
|
Handler: srv.routes(),
|
|
ReadHeaderTimeout: readHeaderTimeout,
|
|
IdleTimeout: idleTimeout,
|
|
}
|
|
|
|
go func() {
|
|
log.Printf("instance %s listening on %s", cfg.InstanceID, httpServer.Addr)
|
|
if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
log.Fatalf("listen: %v", err)
|
|
}
|
|
}()
|
|
|
|
stop := make(chan os.Signal, 1)
|
|
signal.Notify(stop, syscall.SIGTERM, syscall.SIGINT)
|
|
<-stop
|
|
|
|
log.Printf("instance %s shutting down", cfg.InstanceID)
|
|
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
|
|
defer cancel()
|
|
if err := httpServer.Shutdown(ctx); err != nil {
|
|
log.Printf("shutdown: %v", err)
|
|
}
|
|
}
|
|
|
|
func (s *server) routes() http.Handler {
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("GET /health", s.handleHealth)
|
|
mux.HandleFunc("POST /api/auth/login", s.handleLogin)
|
|
mux.HandleFunc("POST /api/auth/logout", s.handleLogout)
|
|
mux.HandleFunc("GET /api/messages", s.handleListMessages)
|
|
mux.HandleFunc("POST /api/messages", s.handleCreateMessage)
|
|
mux.HandleFunc("POST /api/attachments", s.handleUploadAttachment)
|
|
mux.HandleFunc("GET /api/attachments/", s.handleDownloadAttachment)
|
|
return s.addInstanceID(mux)
|
|
}
|
|
|
|
func (s *server) addInstanceID(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set(instanceHeader, s.instance)
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func (s *server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]string{
|
|
"status": "ok",
|
|
"instance": s.instance,
|
|
})
|
|
}
|
|
|
|
func (s *server) handleLogin(w http.ResponseWriter, r *http.Request) {
|
|
var in credentials
|
|
if err := decodeJSON(w, r, &in); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid_request", "malformed json body")
|
|
return
|
|
}
|
|
|
|
in.Login = strings.TrimSpace(in.Login)
|
|
if in.Login == "" || in.Password == "" {
|
|
writeError(w, http.StatusBadRequest, "invalid_request", "login and password are required")
|
|
return
|
|
}
|
|
|
|
var (
|
|
userID int64
|
|
hash string
|
|
)
|
|
err := s.db.QueryRowContext(r.Context(),
|
|
`SELECT id, password_hash FROM users WHERE login = $1`, in.Login).Scan(&userID, &hash)
|
|
if errors.Is(err, sql.ErrNoRows) || (err == nil && !password.Check(in.Password, hash)) {
|
|
writeError(w, http.StatusUnauthorized, "unauthorized", "invalid credentials")
|
|
return
|
|
}
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "login failed")
|
|
return
|
|
}
|
|
|
|
token := ident.GenerateToken()
|
|
expiresAt := time.Now().Add(sessionTTL).UTC()
|
|
if _, err := s.db.ExecContext(r.Context(),
|
|
`INSERT INTO sessions (user_id, token, expires_at) VALUES ($1, $2, $3)`,
|
|
userID, token, expiresAt); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "session create failed")
|
|
return
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, map[string]any{
|
|
"token": token,
|
|
"token_type": "Bearer",
|
|
"expires_at": expiresAt,
|
|
})
|
|
}
|
|
|
|
func (s *server) handleLogout(w http.ResponseWriter, r *http.Request) {
|
|
token, ok := bearerToken(r)
|
|
if !ok {
|
|
writeError(w, http.StatusUnauthorized, "unauthorized", "bearer token required")
|
|
return
|
|
}
|
|
if _, err := s.authenticate(r); err != nil {
|
|
writeError(w, http.StatusUnauthorized, "unauthorized", "invalid or expired session")
|
|
return
|
|
}
|
|
if _, err := s.db.ExecContext(r.Context(), `DELETE FROM sessions WHERE token = $1`, token); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "logout failed")
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
func (s *server) handleListMessages(w http.ResponseWriter, r *http.Request) {
|
|
sess, err := s.authenticate(r)
|
|
if err != nil {
|
|
writeError(w, http.StatusUnauthorized, "unauthorized", "invalid or expired session")
|
|
return
|
|
}
|
|
|
|
rows, err := s.db.QueryContext(r.Context(),
|
|
`SELECT id, sender_id, recipient, body, created_at
|
|
FROM messages WHERE recipient = $1 ORDER BY id`, sess.Login)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "query failed")
|
|
return
|
|
}
|
|
defer rows.Close()
|
|
|
|
items := make([]message, 0)
|
|
for rows.Next() {
|
|
var m message
|
|
if err := rows.Scan(&m.ID, &m.SenderID, &m.Recipient, &m.Body, &m.CreatedAt); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "scan failed")
|
|
return
|
|
}
|
|
m.AttachmentIDs = s.getAttachmentIDs(r.Context(), m.ID)
|
|
items = append(items, m)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "read failed")
|
|
return
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, items)
|
|
}
|
|
|
|
func (s *server) getAttachmentIDs(ctx context.Context, messageID int64) []int64 {
|
|
rows, err := s.db.QueryContext(ctx,
|
|
`SELECT id FROM attachments WHERE message_id = $1 ORDER BY id`, messageID)
|
|
if err != nil {
|
|
return []int64{}
|
|
}
|
|
defer rows.Close()
|
|
|
|
ids := make([]int64, 0)
|
|
for rows.Next() {
|
|
var id int64
|
|
if err := rows.Scan(&id); err == nil {
|
|
ids = append(ids, id)
|
|
}
|
|
}
|
|
return ids
|
|
}
|
|
|
|
func (s *server) handleCreateMessage(w http.ResponseWriter, r *http.Request) {
|
|
sess, err := s.authenticate(r)
|
|
if err != nil {
|
|
writeError(w, http.StatusUnauthorized, "unauthorized", "invalid or expired session")
|
|
return
|
|
}
|
|
|
|
key := strings.TrimSpace(r.Header.Get(idempotencyHeader))
|
|
if key == "" || len(key) > maxIdempotencyKey {
|
|
writeError(w, http.StatusBadRequest, "invalid_request", "Idempotency-Key header is required")
|
|
return
|
|
}
|
|
|
|
var in newMessage
|
|
if err := decodeJSON(w, r, &in); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid_request", "malformed json body")
|
|
return
|
|
}
|
|
in.Recipient = strings.TrimSpace(in.Recipient)
|
|
if in.Recipient == "" || strings.TrimSpace(in.Body) == "" {
|
|
writeError(w, http.StatusBadRequest, "invalid_request", "recipient and body are required")
|
|
return
|
|
}
|
|
|
|
ctx := r.Context()
|
|
tx, err := s.db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "begin transaction failed")
|
|
return
|
|
}
|
|
defer tx.Rollback()
|
|
|
|
var stored []byte
|
|
err = tx.QueryRowContext(ctx,
|
|
`SELECT response FROM idempotency_keys WHERE key = $1 FOR UPDATE`, key).Scan(&stored)
|
|
switch {
|
|
case err == nil:
|
|
if err := tx.Commit(); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "commit failed")
|
|
return
|
|
}
|
|
writeRawJSON(w, http.StatusOK, stored)
|
|
return
|
|
case !errors.Is(err, sql.ErrNoRows):
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "idempotency lookup failed")
|
|
return
|
|
}
|
|
|
|
var msg message
|
|
err = tx.QueryRowContext(ctx,
|
|
`INSERT INTO messages (sender_id, recipient, body)
|
|
VALUES ($1, $2, $3)
|
|
RETURNING id, sender_id, recipient, body, created_at`,
|
|
sess.UserID, in.Recipient, in.Body,
|
|
).Scan(&msg.ID, &msg.SenderID, &msg.Recipient, &msg.Body, &msg.CreatedAt)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "message insert failed")
|
|
return
|
|
}
|
|
|
|
for _, attID := range in.AttachmentIDs {
|
|
_, err := tx.ExecContext(ctx,
|
|
`UPDATE attachments SET message_id = $1 WHERE id = $2 AND message_id IS NULL`,
|
|
msg.ID, attID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "attachment link failed")
|
|
return
|
|
}
|
|
}
|
|
msg.AttachmentIDs = in.AttachmentIDs
|
|
if msg.AttachmentIDs == nil {
|
|
msg.AttachmentIDs = []int64{}
|
|
}
|
|
|
|
payload, err := json.Marshal(msg)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "response encode failed")
|
|
return
|
|
}
|
|
|
|
if _, err := tx.ExecContext(ctx,
|
|
`INSERT INTO idempotency_keys (key, response) VALUES ($1, $2::jsonb)`, key, payload); err != nil {
|
|
tx.Rollback()
|
|
var existing []byte
|
|
if readErr := s.db.QueryRowContext(ctx,
|
|
`SELECT response FROM idempotency_keys WHERE key = $1`, key).Scan(&existing); readErr == nil {
|
|
writeRawJSON(w, http.StatusOK, existing)
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "idempotency store failed")
|
|
return
|
|
}
|
|
|
|
if err := tx.Commit(); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "commit failed")
|
|
return
|
|
}
|
|
|
|
writeRawJSON(w, http.StatusCreated, payload)
|
|
}
|
|
|
|
func (s *server) handleUploadAttachment(w http.ResponseWriter, r *http.Request) {
|
|
sess, err := s.authenticate(r)
|
|
if err != nil {
|
|
writeError(w, http.StatusUnauthorized, "unauthorized", "invalid or expired session")
|
|
return
|
|
}
|
|
_ = sess
|
|
|
|
r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize+1024)
|
|
if err := r.ParseMultipartForm(maxUploadSize); err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid_request", "file too large or invalid multipart")
|
|
return
|
|
}
|
|
|
|
file, header, err := r.FormFile("file")
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid_request", "file field is required")
|
|
return
|
|
}
|
|
defer file.Close()
|
|
|
|
// Проверка опасного имени ДО filepath.Base
|
|
rawName := header.Filename
|
|
if strings.Contains(rawName, "..") || strings.ContainsAny(rawName, "/\\") || strings.HasPrefix(filepath.Base(rawName), ".") {
|
|
writeError(w, http.StatusBadRequest, "invalid_request", "dangerous filename rejected")
|
|
return
|
|
}
|
|
filename := filepath.Base(rawName)
|
|
|
|
data, err := io.ReadAll(io.LimitReader(file, maxUploadSize+1))
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "read failed")
|
|
return
|
|
}
|
|
if int64(len(data)) > maxUploadSize {
|
|
writeError(w, http.StatusBadRequest, "invalid_request", "file exceeds 10 MiB limit")
|
|
return
|
|
}
|
|
|
|
contentType := detectMIME(data)
|
|
if contentType != "image/png" && contentType != "image/jpeg" {
|
|
writeError(w, http.StatusBadRequest, "invalid_request", "only PNG and JPEG allowed")
|
|
return
|
|
}
|
|
|
|
if contentType == "image/jpeg" || contentType == "image/png" {
|
|
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid_request", "cannot decode image dimensions")
|
|
return
|
|
}
|
|
if int64(cfg.Width)*int64(cfg.Height) > maxPixels {
|
|
writeError(w, http.StatusBadRequest, "invalid_request", "image exceeds 40 million pixels")
|
|
return
|
|
}
|
|
}
|
|
|
|
keyBytes := make([]byte, 16)
|
|
rand.Read(keyBytes)
|
|
s3Key := hex.EncodeToString(keyBytes)
|
|
|
|
hash := sha256.Sum256(data)
|
|
checksum := hex.EncodeToString(hash[:])
|
|
|
|
// Таймаут 5 секунд для S3 — чтобы быстро вернуть 503, а не ждать 504 от HAProxy
|
|
s3Ctx, s3Cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
|
defer s3Cancel()
|
|
|
|
err = s3.UploadFile(s3Ctx, s.s3Client, s.s3Bucket, s3Key, bytes.NewReader(data), int64(len(data)), contentType)
|
|
if err != nil {
|
|
writeError(w, http.StatusServiceUnavailable, "s3_unavailable", "S3 storage unavailable")
|
|
return
|
|
}
|
|
|
|
// ИСПРАВЛЕНО: используем r.Context() вместо несуществующего ctx
|
|
var attID int64
|
|
err = s.db.QueryRowContext(r.Context(),
|
|
`INSERT INTO attachments (s3_key, filename, content_type, size, checksum)
|
|
VALUES ($1, $2, $3, $4, $5) RETURNING id`,
|
|
s3Key, filename, contentType, len(data), checksum).Scan(&attID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "metadata save failed")
|
|
return
|
|
}
|
|
|
|
writeJSON(w, http.StatusCreated, map[string]any{
|
|
"id": attID,
|
|
"filename": filename,
|
|
"content_type": contentType,
|
|
"size": len(data),
|
|
"checksum": checksum,
|
|
"status": "ready",
|
|
})
|
|
}
|
|
|
|
func (s *server) handleDownloadAttachment(w http.ResponseWriter, r *http.Request) {
|
|
sess, err := s.authenticate(r)
|
|
if err != nil {
|
|
writeError(w, http.StatusUnauthorized, "unauthorized", "invalid or expired session")
|
|
return
|
|
}
|
|
|
|
idStr := strings.TrimPrefix(r.URL.Path, "/api/attachments/")
|
|
attID, err := strconv.ParseInt(idStr, 10, 64)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid_request", "invalid attachment id")
|
|
return
|
|
}
|
|
|
|
var s3Key, filename, contentType string
|
|
var size int64
|
|
var messageID sql.NullInt64
|
|
var uploaderUserID sql.NullInt64
|
|
err = s.db.QueryRowContext(r.Context(),
|
|
`SELECT a.s3_key, a.filename, a.content_type, a.size, a.message_id,
|
|
(SELECT sender_id FROM messages WHERE id = a.message_id)
|
|
FROM attachments a WHERE a.id = $1`,
|
|
attID).Scan(&s3Key, &filename, &contentType, &size, &messageID, &uploaderUserID)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
writeError(w, http.StatusNotFound, "not_found", "attachment not found")
|
|
return
|
|
}
|
|
if err != nil {
|
|
// Fallback: если в таблице нет колонки uploader — используем простой запрос
|
|
err = s.db.QueryRowContext(r.Context(),
|
|
`SELECT s3_key, filename, content_type, size, message_id FROM attachments WHERE id = $1`,
|
|
attID).Scan(&s3Key, &filename, &contentType, &size, &messageID)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
writeError(w, http.StatusNotFound, "not_found", "attachment not found")
|
|
return
|
|
}
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal_error", "query failed")
|
|
return
|
|
}
|
|
}
|
|
|
|
// Проверка прав доступа
|
|
if messageID.Valid {
|
|
var senderID int64
|
|
var recipient string
|
|
err = s.db.QueryRowContext(r.Context(),
|
|
`SELECT sender_id, recipient FROM messages WHERE id = $1`, messageID.Int64).Scan(&senderID, &recipient)
|
|
if err != nil {
|
|
writeError(w, http.StatusNotFound, "not_found", "message not found")
|
|
return
|
|
}
|
|
if senderID != sess.UserID && recipient != sess.Login {
|
|
writeError(w, http.StatusForbidden, "forbidden", "access denied")
|
|
return
|
|
}
|
|
}
|
|
|
|
// Таймаут 5 секунд для S3
|
|
s3Ctx, s3Cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
|
defer s3Cancel()
|
|
|
|
obj, err := s3.DownloadFile(s3Ctx, s.s3Client, s.s3Bucket, s3Key)
|
|
if err != nil {
|
|
writeError(w, http.StatusServiceUnavailable, "s3_unavailable", "S3 storage unavailable")
|
|
return
|
|
}
|
|
defer obj.Close()
|
|
|
|
w.Header().Set("Content-Type", contentType)
|
|
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
|
|
w.Header().Set("Content-Length", strconv.FormatInt(size, 10))
|
|
w.WriteHeader(http.StatusOK)
|
|
io.Copy(w, obj)
|
|
}
|
|
|
|
func detectMIME(data []byte) string {
|
|
if len(data) >= 8 && data[0] == 0x89 && data[1] == 0x50 && data[2] == 0x4E && data[3] == 0x47 {
|
|
return "image/png"
|
|
}
|
|
if len(data) >= 3 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF {
|
|
return "image/jpeg"
|
|
}
|
|
return http.DetectContentType(data)
|
|
}
|
|
|
|
func (s *server) authenticate(r *http.Request) (*session, error) {
|
|
token, ok := bearerToken(r)
|
|
if !ok {
|
|
return nil, errNoSession
|
|
}
|
|
|
|
var sess session
|
|
err := s.db.QueryRowContext(r.Context(),
|
|
`SELECT s.user_id, u.login
|
|
FROM sessions s
|
|
JOIN users u ON u.id = s.user_id
|
|
WHERE s.token = $1 AND s.expires_at > NOW()`, token).Scan(&sess.UserID, &sess.Login)
|
|
if err != nil {
|
|
return nil, errNoSession
|
|
}
|
|
return &sess, nil
|
|
}
|
|
|
|
func bearerToken(r *http.Request) (string, bool) {
|
|
header := r.Header.Get("Authorization")
|
|
const prefix = "Bearer "
|
|
if len(header) <= len(prefix) || !strings.EqualFold(header[:len(prefix)], prefix) {
|
|
return "", false
|
|
}
|
|
token := strings.TrimSpace(header[len(prefix):])
|
|
if token == "" {
|
|
return "", false
|
|
}
|
|
return token, true
|
|
}
|
|
|
|
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) error {
|
|
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
|
|
decoder := json.NewDecoder(r.Body)
|
|
return decoder.Decode(dst)
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, body any) {
|
|
payload, err := json.Marshal(body)
|
|
if err != nil {
|
|
http.Error(w, "response encode failed", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
writeRawJSON(w, status, payload)
|
|
}
|
|
|
|
func writeRawJSON(w http.ResponseWriter, status int, payload []byte) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
w.Write(payload)
|
|
}
|
|
|
|
func writeError(w http.ResponseWriter, status int, code, message string) {
|
|
writeJSON(w, status, map[string]any{
|
|
"error": map[string]string{
|
|
"code": code,
|
|
"message": message,
|
|
},
|
|
})
|
|
}
|