summary refs log tree commit diff stats
path: root/hibp/req.go
blob: 8081d3c97100b02d83e70627c0c65654f97123ec (plain) (blame)
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
package hibp

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

func reqHIBP(reqApi string) (body string, err error) {
	c := http.Client{
		// TODO: timeout should be configurable by the user
		Timeout: time.Second * 64,
	}

	req, err := http.NewRequest(http.MethodGet, reqApi, nil)
	if err != nil {
		err = fmt.Errorf("hibp/req.go: Failed to create request\n%s",
			err.Error())
		return
	}

	// User-Agent should be passed with every request to
	// make work easier for the server handler. Include contact
	// information along with the project name so they could reach
	// you if required.
	req.Header.Set("User-Agent",
		"Andinus / Orion - https://andinus.nand.sh/orion")

	res, err := c.Do(req)
	if err != nil {
		err = fmt.Errorf("hibp/req.go: Failed to get response\n%s",
			err.Error())
		return
	}
	defer res.Body.Close()

	if res.StatusCode != 200 {
		fmt.Errorf("hibp/req.go: Unexpected response status code received: %d %s",
			res.StatusCode,
			http.StatusText(res.StatusCode))
		return
	}

	// This will read everything to memory and is okay to use here
	// because the response is expected to be small.
	out, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Errorf("hibp/req.go: Failed to read res.Body\n%s",
			err.Error())
		return
	}

	body = string(out)
	return
}