aboutsummaryrefslogtreecommitdiff
path: root/cmd/main/http.go
blob: ef6f2a7ef3547640aa91cc7b41f1084af2bed788 (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"
)

type httpCheck struct {
	URL  string
	Code int
}

type httpCheckFunc func(string, int, int) error

func httpStatusWorker(jobs <-chan httpCheck, msg chan<- *jobResponse, timeout int, HF httpCheckFunc) {
	for hc := range jobs {
		err := HF(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, data map[string]*int, HF httpCheckFunc) 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, HF)
	}

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

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

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

	return out
}