Home | History | Annotate | Download | only in handlers
      1 package handlers
      2 
      3 import (
      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 
     16 var globalJobStatus = constants.JobStatusNotStarted
     17 var globalMeta string
     18 var globalStartTime time.Time
     19 
     20 type 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 
     27 func 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 
     36 func 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 
     51 func listenForStatusChanges(statusChannel chan e.StatusMessage) {
     52 	for {
     53 		m := <-statusChannel
     54 		globalJobStatus = m.JobStatus
     55 		globalMeta = m.Meta
     56 	}
     57 }
     58 
     59 func 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