aboutsummaryrefslogtreecommitdiff
path: root/web/switchcounter/switchc.go
blob: b74eb4285f5a40a9909195e0732e3f5fa0933b4a (plain)
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
// Package switchcounter is a simple interface to the https://www.switchcounter.science/ API.
package switchcounter

import (
	"bytes"
	"encoding/json"
	"net/http"
	"time"
)

type arg struct {
	Command    string `json:"command"` // always "switch"
	MemberName string `json:"member_name,omitempty"`
}

// Status is the API response.
type Status struct {
	Front     string    `json:"member_name"`
	StartedAt time.Time `json:"started_at"`
}

type API struct {
	url string // webhook url
}

func (a API) makeRequestWith(body interface{}) (*http.Request, error) {
	env := struct {
		Webhook interface{} `json:"webhook"`
	}{
		Webhook: body,
	}
	data, err := json.Marshal(env)
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest(http.MethodPost, a.url, bytes.NewBuffer(data))
	if err != nil {
		return nil, err
	}
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")

	return req, nil
}

func (a API) Status() *http.Request {
	result, err := a.makeRequestWith(arg{Command: "switch"})
	if err != nil {
		panic(err)
	}
	return result
}

func (a API) Switch(front string) *http.Request {
	result, err := a.makeRequestWith(arg{Command: "switch", MemberName: front})
	if err != nil {
		panic(err)
	}
	return result
}

// NewHTTPClient creates a new instance of API over HTTP.
func NewHTTPClient(a *http.Client, webhookURL string) API {
	return API{
		url: webhookURL,
	}
}