aboutsummaryrefslogtreecommitdiff
path: root/cmd/main/http.go
blob: 8eb4990c9a21a41a1b0b826ae01fd6c36b08cbcc (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
57
58
59
60
61
62
63
64
65
66
package main

import (
	"bytes"
	"fmt"
	"time"

	"riedstra.dev/go/checkup"
)

type httpCheck struct {
	URL  string
	Code int
}

func httpStatusWorker(jobs <-chan httpCheck, msg chan<- *jobResponse, timeout int) {
	for hc := range jobs {
		err := checkup.HttpStatusOK(hc.URL, timeout, hc.Code)
		if err != nil {
			s := fmt.Sprintf("Checking: %s, %v",
				hc.URL, err)
			msg <- &jobResponse{
				Id:      hc.URL + "->" + string(hc.Code),
				Message: s,
				Err:     err,
				Time:    time.Now(),
			}
			continue
		}
		msg <- nil
	}
}

func checkStatus(conf *Config) map[string]*jobResponse {
	buf := &bytes.Buffer{}

	hc := make(chan httpCheck)
	msgs := make(chan *jobResponse)

	for i := 1; i <= conf.Workers; i++ {
		go httpStatusWorker(hc, msgs, conf.HTTPTimeout)
	}

	go func() {
		for url, code := range conf.StatusChecks {
			if code == nil {
				code = &conf.ExpectedStatusCode
			}
			hc <- httpCheck{url, *code}
		}
		close(hc)
	}()

	out := make(map[string]*jobResponse)
	for i := 0; i < len(conf.StatusChecks); i++ {
		resp := <-msgs
		if resp != nil {
			buf.Write([]byte(resp.Message))
			out[resp.Id] = resp
		}
	}

	// notify(conf, buf.Bytes())

	return out
}