Debian Codegraph @

pkg/http/http.go

raw
1 package http
2
3 import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "io"
8 "log"
9 "net/http"
10 "net/url"
11 "strings"
12 "time"
13
14 "github.com/zitadel/oidc/v3/pkg/oidc"
15 )
16
17 var DefaultHTTPClient = &http.Client{
18 Timeout: 30 * time.Second,
19 }
20
21 type Decoder interface {
22 Decode(dst any, src map[string][]string) error
23 }
24
25 type Encoder interface {
26 Encode(src any, dst map[string][]string) error
27 }
28
29 type (
30 FormAuthorization func(url.Values)
31 RequestAuthorization func(*http.Request)
32 )
33
34 func AuthorizeBasic(user, password string) RequestAuthorization {
35 return func(req *http.Request) {
36 req.SetBasicAuth(url.QueryEscape(user), url.QueryEscape(password))
37 }
38 }
39
40 func FormRequest(ctx context.Context, endpoint string, request any, encoder Encoder, authFn any) (*http.Request, error) {
41 form := url.Values{}
42 if err := encoder.Encode(request, form); err != nil {
43 return nil, err
44 }
45 if fn, ok := authFn.(FormAuthorization); ok && fn != nil {
46 fn(form)
47 }
48 body := strings.NewReader(form.Encode())
49 req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, body)
50 if err != nil {
51 return nil, err
52 }
53 if fn, ok := authFn.(RequestAuthorization); ok && fn != nil {
54 fn(req)
55 }
56 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
57 return req, nil
58 }
59
60 func HttpRequest(client *http.Client, req *http.Request, response any) error {
61 resp, err := client.Do(req)
62 if err != nil {
63 return err
64 }
65 defer resp.Body.Close()
66
67 body, err := io.ReadAll(io.LimitReader(resp.Body, MaxResponseBodySize+1))
68 if err != nil {
69 return fmt.Errorf("unable to read response body: %v", err)
70 }
71
72 if resp.StatusCode != http.StatusOK {
73 var oidcErr oidc.Error
74 err = json.Unmarshal(body, &oidcErr)
75 if err != nil || oidcErr.ErrorType == "" {
76 return fmt.Errorf("http status not ok: %s %s", resp.Status, body)
77 }
78 return &oidcErr
79 }
80
81 if int64(len(body)) > MaxResponseBodySize {
82 return ErrResponseBodyTooLarge
83 }
84
85 err = json.Unmarshal(body, response)
86 if err != nil {
87 return fmt.Errorf("failed to unmarshal response: %v %s", err, body)
88 }
89 return nil
90 }
91
92 func URLEncodeParams(resp any, encoder Encoder) (url.Values, error) {
93 values := make(map[string][]string)
94 err := encoder.Encode(resp, values)
95 if err != nil {
96 return nil, err
97 }
98 return values, nil
99 }
100
101 func StartServer(ctx context.Context, address string) {
102 server := &http.Server{Addr: address}
103 go func() {
104 if err := server.ListenAndServe(); err != http.ErrServerClosed {
105 log.Fatalf("ListenAndServe(): %v", err)
106 }
107 }()
108
109 go func() {
110 <-ctx.Done()
111 ctxShutdown, cancelShutdown := context.WithTimeout(context.Background(), 5*time.Second)
112 defer cancelShutdown()
113 err := server.Shutdown(ctxShutdown)
114 if err != nil {
115 log.Fatalf("Shutdown(): %v", err)
116 }
117 }()
118 }