-
Notifications
You must be signed in to change notification settings - Fork 0
/
optic.go
51 lines (45 loc) · 1.13 KB
/
optic.go
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
45
46
47
48
49
50
51
// Package optic a generic net/http extension that makes exchanging data in go really fun
package optic
import (
"encoding/json"
"fmt"
"net/http"
)
const (
defaultBasePath = "/"
)
// HTTPError optic needs a http.StatusCode to properly send the response
// otherwise HTTPError can be any go struct
type HTTPError interface {
GetCode() int
}
// Empty is useful when you want to Glance with no input struct
type Empty struct{}
// FromResponse decodes the net/http Response.Body into the desired struct
// exporting because FromResponse is useful on it's own in normal net/http handlers
func FromResponse(res *http.Response, recieved any) error {
var (
err error
)
defer res.Body.Close()
if res.StatusCode == http.StatusOK {
err = json.NewDecoder(res.Body).Decode(recieved)
if err != nil {
return err
}
return nil
}
return fmt.Errorf("The response failed with status %s", res.Status)
}
func getHTTPErrorFromResponse[E any](res *http.Response) (E, error) {
var (
err error
httpErr E
)
defer res.Body.Close()
err = json.NewDecoder(res.Body).Decode(&httpErr)
if err != nil {
return httpErr, err
}
return httpErr, nil
}