Debian Codegraph @

internal/httperror/response.go

raw symbols SCIP
1 package httperror
2
3 import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 "strings"
9 )
10
11 type ResponseError struct {
12 Method string
13 URL string
14 Status string
15 StatusCode int
16 BodyText string
17 }
18
19 func (e ResponseError) Error() string {
20 return fmt.Sprintf("HTTP error:\n%s %s\n%s\n%s", e.Method, e.URL, e.Status, e.BodyText)
21 }
22
23 func (e ResponseError) Temporary() bool {
24 return statusIsTemporary(e.StatusCode)
25 }
26
27 func FromResponse(resp *http.Response) error {
28 defer resp.Body.Close()
29 blob, err := io.ReadAll(io.LimitReader(resp.Body, 100000))
30 if err != nil {
31 return err
32 }
33 if strings.Contains(resp.Header.Get("Content-Type"), "problem+json") {
34 var p Problem
35 if err := json.Unmarshal(blob, &p); err == nil {
36 if p.Status == 0 {
37 p.Status = resp.StatusCode
38 }
39 return p
40 }
41 }
42 return ResponseError{
43 Method: resp.Request.Method,
44 URL: resp.Request.URL.String(),
45 Status: resp.Status,
46 StatusCode: resp.StatusCode,
47 BodyText: string(blob),
48 }
49 }
50
51 func statusIsTemporary(code int) bool {
52 switch code {
53 case http.StatusGatewayTimeout,
54 http.StatusBadGateway,
55 http.StatusServiceUnavailable,
56 http.StatusInsufficientStorage,
57 http.StatusInternalServerError:
58 return true
59 default:
60 return false
61 }
62 }