github.com/keybase/client/go@v0.0.0-20240309051027-028f7c731f8b/libkb/http.go (about) 1 // Copyright 2015 Keybase, Inc. All rights reserved. Use of 2 // this source code is governed by the included BSD license. 3 4 package libkb 5 6 import ( 7 "encoding/base64" 8 "encoding/hex" 9 "fmt" 10 "net/http" 11 "net/url" 12 "strconv" 13 14 keybase1 "github.com/keybase/client/go/protocol/keybase1" 15 ) 16 17 type HTTPValue interface { 18 String() string 19 } 20 21 type HTTPArgs map[string]HTTPValue 22 23 type S struct { 24 Val string 25 } 26 27 func HexArg(b []byte) S { 28 return S{Val: hex.EncodeToString(b)} 29 } 30 31 func B64Arg(b []byte) S { 32 return S{Val: base64.StdEncoding.EncodeToString(b)} 33 } 34 35 type I struct { 36 Val int 37 } 38 39 type I64 struct { 40 Val int64 41 } 42 43 type U struct { 44 Val uint64 45 } 46 47 type UHex struct { 48 Val uint64 49 } 50 51 type B struct { 52 Val bool 53 } 54 55 type HTTPTime struct { 56 Val keybase1.Time 57 } 58 59 func (a *HTTPArgs) Add(s string, v HTTPValue) { 60 (*a)[s] = v 61 } 62 63 func NewHTTPArgs() HTTPArgs { 64 return make(HTTPArgs) 65 } 66 67 func (s S) String() string { return s.Val } 68 func (i I) String() string { return strconv.Itoa(i.Val) } 69 func (i I64) String() string { return strconv.FormatInt(i.Val, 10) } 70 func (u U) String() string { return strconv.FormatUint(u.Val, 10) } 71 func (h UHex) String() string { return fmt.Sprintf("%016x", h.Val) } 72 func (b B) String() string { 73 if b.Val { 74 return "1" 75 } 76 return "0" 77 } 78 func (t HTTPTime) String() string { return strconv.FormatInt(int64(t.Val), 10) } 79 80 func (a HTTPArgs) ToValues() url.Values { 81 ret := url.Values{} 82 for k, v := range a { 83 ret.Set(k, v.String()) 84 } 85 return ret 86 } 87 88 func (a HTTPArgs) EncodeToString() string { 89 return a.ToValues().Encode() 90 } 91 92 func HTTPArgsFromKeyValuePair(key string, val HTTPValue) HTTPArgs { 93 ret := HTTPArgs{} 94 ret[key] = val 95 return ret 96 } 97 98 type ClosingRoundTripper struct { 99 rt http.RoundTripper 100 } 101 102 func NewClosingRoundTripper(rt http.RoundTripper) *ClosingRoundTripper { 103 return &ClosingRoundTripper{ 104 rt: rt, 105 } 106 } 107 108 func (t ClosingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { 109 req.Close = true 110 return t.rt.RoundTrip(req) 111 }