forked from harness/gitness
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
82 lines (71 loc) · 1.58 KB
/
http.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package internal
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"net/url"
)
// Send makes an http request to the given endpoint, writing the input
// to the request body and unmarshaling the output from the response body.
func Send(method, path string, in, out interface{}) error {
uri, err := url.Parse(path)
if err != nil {
return err
}
// if we are posting or putting data, we need to
// write it to the body of the request.
var buf io.ReadWriter
if in != nil {
buf = new(bytes.Buffer)
jsonerr := json.NewEncoder(buf).Encode(in)
if jsonerr != nil {
return jsonerr
}
}
// creates a new http request to bitbucket.
req, err := http.NewRequest(method, uri.String(), buf)
if err != nil {
return err
}
if in != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// if an error is encountered, parse and return the
// error response.
if resp.StatusCode > http.StatusPartialContent {
out, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return &Error{
code: resp.StatusCode,
text: string(out),
}
}
// if a json response is expected, parse and return
// the json response.
if out != nil {
return json.NewDecoder(resp.Body).Decode(out)
}
return nil
}
// Error represents a http error.
type Error struct {
code int
text string
}
// Code returns the http error code.
func (e *Error) Code() int {
return e.code
}
// Error returns the error message in string format.
func (e *Error) Error() string {
return e.text
}