-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathresponse.go
More file actions
44 lines (40 loc) · 1.21 KB
/
response.go
File metadata and controls
44 lines (40 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package server
import (
"context"
"encoding/json"
"errors"
"log"
"net/http"
)
// writeJSON writes v as JSON with the given HTTP status code.
// Logs a warning if JSON encoding fails.
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(v); err != nil {
log.Printf("writeJSON: encoding response: %v", err)
}
}
// writeError writes a JSON error response with the given status
// and message.
func writeError(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]string{"error": msg})
}
// handleContextError checks for context.Canceled and
// context.DeadlineExceeded. On cancellation it returns true
// silently (client disconnected). On deadline exceeded it
// writes a 504 and returns true. Behind withTimeout the 504
// goes into the TimeoutHandler buffer and is discarded if
// the middleware fires first.
func handleContextError(w http.ResponseWriter, err error) bool {
if errors.Is(err, context.Canceled) {
return true
}
if errors.Is(err, context.DeadlineExceeded) {
writeError(
w, http.StatusGatewayTimeout, "gateway timeout",
)
return true
}
return false
}