forked from df-mc/go-xsapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransport.go
63 lines (54 loc) · 1.42 KB
/
transport.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
52
53
54
55
56
57
58
59
60
61
62
63
package xsapi
import (
"errors"
"net/http"
)
// Transport is an http.RoundTripper that makes authenticated Xbox Live requests,
// wrapping a base RoundTripper and adding an 'Authorization' header and a 'Signature'
// header with a token from the supplied Sources.
type Transport struct {
Source TokenSource
Base http.RoundTripper
}
// RoundTrip authorizes and authenticates the request using the
// [Token.SetAuthHeader] from Source of the Transport.
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
reqBodyClosed := false
if req.Body != nil {
defer func() {
if !reqBodyClosed {
req.Body.Close()
}
}()
}
if t.Source == nil {
return nil, errors.New("xsapi: Transport's Source is nil")
}
token, err := t.Source.Token()
if err != nil {
return nil, err
}
req2 := cloneRequest(req)
token.SetAuthHeader(req2)
reqBodyClosed = true
return t.base().RoundTrip(req2)
}
func (t *Transport) base() http.RoundTripper {
if t.Base != nil {
return t.Base
}
return http.DefaultTransport
}
// cloneRequest returns a clone of the provided *http.Request.
// The clone is a shallow copy of the struct and its Header map.
func cloneRequest(r *http.Request) *http.Request {
// shallow copy of the struct
r2 := new(http.Request)
*r2 = *r
// deep copy of the Header
r2.Header = make(http.Header, len(r.Header))
for k, s := range r.Header {
r2.Header[k] = append([]string(nil), s...)
}
return r2
}