1package handlers
2
3import (
4	"encoding/json"
5	"fmt"
6	"log"
7	"net/http"
8	"time"
9
10	"github.com/pkg/errors"
11
12	"repodiff/constants"
13	e "repodiff/entities"
14)
15
16var globalJobStatus = constants.JobStatusNotStarted
17var globalMeta string
18var globalStartTime time.Time
19
20type healthResponse struct {
21	ApplicationStatus string `json:"application_status"`
22	JobStatus         string `json:"job_status"`
23	Meta              string `json:"meta"`
24	ElapsedTime       string `json:"elapsed_time"`
25}
26
27func writeJsonResponse(writer http.ResponseWriter, entity interface{}) {
28	serialized, err := json.MarshalIndent(entity, "", "    ")
29	if err != nil {
30		log.Fatal(err)
31	}
32	writer.Header().Set("Content-Type", "application/json")
33	writer.Write(serialized)
34}
35
36func handleHealth(writer http.ResponseWriter, request *http.Request) {
37	switch request.Method {
38	case "GET":
39		writeJsonResponse(
40			writer,
41			healthResponse{
42				ApplicationStatus: "ok",
43				JobStatus:         globalJobStatus,
44				Meta:              globalMeta,
45				ElapsedTime:       fmt.Sprintf("%s", time.Now().Sub(globalStartTime)),
46			},
47		)
48	}
49}
50
51func listenForStatusChanges(statusChannel chan e.StatusMessage) {
52	for {
53		m := <-statusChannel
54		globalJobStatus = m.JobStatus
55		globalMeta = m.Meta
56	}
57}
58
59func StartHTTP(servePort int, statusChannel chan e.StatusMessage) error {
60	globalStartTime = time.Now()
61	go listenForStatusChanges(statusChannel)
62	http.HandleFunc("/health", handleHealth)
63	return errors.Wrap(
64		http.ListenAndServe(
65			fmt.Sprintf(":%d", servePort),
66			nil,
67		),
68		"Error starting web server",
69	)
70}
71