-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest_keys.go
63 lines (54 loc) · 1.17 KB
/
request_keys.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 main
import (
"bufio"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"time"
)
// GetUserPubKeys makes a request for plain-text public keys for a given user.
func GetUserPubKeys(w io.Writer, user string) error {
// Keys endpoint.
reqEndpoint := keysEndpoint + "/" + user + "/text"
// Make request.
req, err := http.NewRequest("GET", reqEndpoint, nil)
if err != nil {
fmt.Fprintf(w, "Error building request: %s\n", err)
return err
}
// Create HTTP client with timeout of 5s.
client := &http.Client{
Timeout: time.Second * 5,
}
// Make HTTP request.
resp, err := client.Do(req)
if err != nil {
fmt.Fprintf(w, "Error making request: %s\n", err)
return err
}
defer resp.Body.Close()
// Check if request was successful.
if resp.StatusCode == http.StatusOK {
// Pass public keys to stdout.
reader := bufio.NewReader(resp.Body)
for {
key, err := reader.ReadString('\n')
if err != nil {
if err == io.EOF {
break
}
return err
}
fmt.Fprintf(w, "%s", key)
}
} else { // API call returned an error.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return errors.New(string(body))
}
return nil
}