A community based topic aggregation platform built on atproto
1package post
2
3import (
4 "encoding/json"
5 "log"
6 "net/http"
7
8 "Coves/internal/core/aggregators"
9 "Coves/internal/core/posts"
10)
11
12type errorResponse struct {
13 Error string `json:"error"`
14 Message string `json:"message"`
15}
16
17// writeError writes a JSON error response
18func writeError(w http.ResponseWriter, statusCode int, errorType, message string) {
19 w.Header().Set("Content-Type", "application/json")
20 w.WriteHeader(statusCode)
21 if err := json.NewEncoder(w).Encode(errorResponse{
22 Error: errorType,
23 Message: message,
24 }); err != nil {
25 log.Printf("Failed to encode error response: %v", err)
26 }
27}
28
29// handleServiceError maps service errors to HTTP responses
30func handleServiceError(w http.ResponseWriter, err error) {
31 switch {
32 case err == posts.ErrCommunityNotFound:
33 writeError(w, http.StatusNotFound, "CommunityNotFound",
34 "Community not found")
35
36 case err == posts.ErrNotAuthorized:
37 writeError(w, http.StatusForbidden, "NotAuthorized",
38 "You are not authorized to post in this community")
39
40 case err == posts.ErrBanned:
41 writeError(w, http.StatusForbidden, "Banned",
42 "You are banned from this community")
43
44 case posts.IsContentRuleViolation(err):
45 writeError(w, http.StatusBadRequest, "ContentRuleViolation", err.Error())
46
47 case posts.IsValidationError(err):
48 writeError(w, http.StatusBadRequest, "InvalidRequest", err.Error())
49
50 case posts.IsNotFound(err):
51 writeError(w, http.StatusNotFound, "NotFound", err.Error())
52
53 // Check both aggregator and post rate limit errors
54 case aggregators.IsRateLimited(err) || err == posts.ErrRateLimitExceeded:
55 writeError(w, http.StatusTooManyRequests, "RateLimitExceeded",
56 "Rate limit exceeded. Please try again later.")
57
58 default:
59 // Don't leak internal error details to clients
60 log.Printf("Unexpected error in post handler: %v", err)
61 writeError(w, http.StatusInternalServerError, "InternalServerError",
62 "An internal error occurred")
63 }
64}