1
0
Fork 0
mirror of https://github.com/TwiN/gatus.git synced 2024-12-14 11:58:04 +00:00

Support Gzip and cache result to prevent wasting CPU

This commit is contained in:
TwinProduction 2020-08-15 16:44:28 -04:00
parent 7849cc6dd4
commit 1f241ecdb3

44
main.go
View file

@ -1,6 +1,8 @@
package main package main
import ( import (
"bytes"
"compress/gzip"
"encoding/json" "encoding/json"
"github.com/TwinProduction/gatus/config" "github.com/TwinProduction/gatus/config"
"github.com/TwinProduction/gatus/watchdog" "github.com/TwinProduction/gatus/watchdog"
@ -8,6 +10,16 @@ import (
"log" "log"
"net/http" "net/http"
"os" "os"
"strings"
"time"
)
const CacheTTL = 10 * time.Second
var (
cachedServiceResults []byte
cachedServiceResultsGzipped []byte
cachedServiceResultsTimestamp time.Time
) )
func main() { func main() {
@ -37,14 +49,30 @@ func loadConfiguration() *config.Config {
return config.Get() return config.Get()
} }
func serviceResultsHandler(writer http.ResponseWriter, _ *http.Request) { func serviceResultsHandler(writer http.ResponseWriter, r *http.Request) {
serviceResults := watchdog.GetServiceResults() if isExpired := cachedServiceResultsTimestamp.IsZero() || time.Now().Sub(cachedServiceResultsTimestamp) > CacheTTL; isExpired {
data, err := json.Marshal(serviceResults) buffer := &bytes.Buffer{}
if err != nil { gzipWriter := gzip.NewWriter(buffer)
log.Printf("[main][serviceResultsHandler] Unable to marshall object to JSON: %s", err.Error()) serviceResults := watchdog.GetServiceResults()
writer.WriteHeader(http.StatusInternalServerError) data, err := json.Marshal(serviceResults)
_, _ = writer.Write([]byte("Unable to marshall object to JSON")) if err != nil {
return log.Printf("[main][serviceResultsHandler] Unable to marshall object to JSON: %s", err.Error())
writer.WriteHeader(http.StatusInternalServerError)
_, _ = writer.Write([]byte("Unable to marshall object to JSON"))
return
}
gzipWriter.Write(data)
gzipWriter.Close()
cachedServiceResults = data
cachedServiceResultsGzipped = buffer.Bytes()
cachedServiceResultsTimestamp = time.Now()
}
var data []byte
if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
writer.Header().Set("Content-Encoding", "gzip")
data = cachedServiceResultsGzipped
} else {
data = cachedServiceResults
} }
writer.Header().Add("Content-type", "application/json") writer.Header().Add("Content-type", "application/json")
writer.WriteHeader(http.StatusOK) writer.WriteHeader(http.StatusOK)