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