Write on the margins of the internet. Powered by the AT Protocol.
margin.at
extension
web
atproto
comments
1package api
2
3import (
4 "encoding/json"
5 "net/http"
6)
7
8type APIError struct {
9 Error string `json:"error"`
10 Code string `json:"code,omitempty"`
11 Details string `json:"details,omitempty"`
12}
13
14func WriteJSONError(w http.ResponseWriter, statusCode int, message string) {
15 w.Header().Set("Content-Type", "application/json")
16 w.WriteHeader(statusCode)
17 json.NewEncoder(w).Encode(APIError{Error: message})
18}
19
20func WriteJSONErrorWithCode(w http.ResponseWriter, statusCode int, message, code string) {
21 w.Header().Set("Content-Type", "application/json")
22 w.WriteHeader(statusCode)
23 json.NewEncoder(w).Encode(APIError{Error: message, Code: code})
24}
25
26func WriteJSON(w http.ResponseWriter, statusCode int, data interface{}) {
27 w.Header().Set("Content-Type", "application/json")
28 w.WriteHeader(statusCode)
29 json.NewEncoder(w).Encode(data)
30}
31
32func WriteSuccess(w http.ResponseWriter, data interface{}) {
33 WriteJSON(w, http.StatusOK, data)
34}
35
36func WriteBadRequest(w http.ResponseWriter, message string) {
37 WriteJSONError(w, http.StatusBadRequest, message)
38}
39
40func WriteUnauthorized(w http.ResponseWriter, message string) {
41 WriteJSONError(w, http.StatusUnauthorized, message)
42}
43
44func WriteForbidden(w http.ResponseWriter, message string) {
45 WriteJSONError(w, http.StatusForbidden, message)
46}
47
48func WriteNotFound(w http.ResponseWriter, message string) {
49 WriteJSONError(w, http.StatusNotFound, message)
50}
51
52func WriteConflict(w http.ResponseWriter, message string) {
53 WriteJSONError(w, http.StatusConflict, message)
54}
55
56func WriteInternalError(w http.ResponseWriter, message string) {
57 WriteJSONError(w, http.StatusInternalServerError, message)
58}