server: Add HTTP server

0.1.0
Luther Wen Xu 2020-04-23 15:42:16 +07:00
parent 5f14a5b943
commit 81e74807f4
Signed by: chanbakjsd
GPG Key ID: B7D77E3E9D102B70
5 changed files with 65 additions and 1 deletions

@ -7,6 +7,7 @@ import (
type Config struct { type Config struct {
Targets []checkTarget Targets []checkTarget
Port int
} }
func ReadConfig(file string) (Config, error) { func ReadConfig(file string) (Config, error) {

@ -1,9 +1,14 @@
package main package main
import (
"status/server"
)
func main() { func main() {
cfg, err := ReadConfig("config.json") cfg, err := ReadConfig("config.json")
if err != nil { if err != nil {
panic(err) panic(err)
} }
checkLoop(cfg.Targets) go checkLoop(cfg.Targets)
server.StartServer(cfg.Port)
} }

@ -0,0 +1,20 @@
package server
import (
"encoding/json"
"net/http"
)
func writeJSON(w http.ResponseWriter, a interface{}) {
bytes, err := json.Marshal(a)
if err != nil {
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
}
w.Header().Set("Content-Type", "application/json")
w.Write(bytes)
}
func allStatus(w http.ResponseWriter, req *http.Request) {
status := getStatus()
writeJSON(w, status)
}

@ -0,0 +1,19 @@
package server
import (
"time"
"status/db"
)
func getStatus() map[string]db.PingEntry {
entries := db.GetFromDB("", time.Now().Add(time.Duration(-2)*time.Minute), time.Now())
result := make(map[string]db.PingEntry)
for _, v := range entries {
if v.Time.Before(result[v.ServiceName].Time) {
continue
}
result[v.ServiceName] = v
}
return result
}

@ -0,0 +1,19 @@
package server
import (
"fmt"
"net/http"
"strconv"
)
func apiEndpoints() {
http.HandleFunc("/api/latest", allStatus)
}
func StartServer(port int) {
apiEndpoints()
err := http.ListenAndServe(":"+strconv.Itoa(port), nil)
if err != nil {
fmt.Printf("ListenAndServe returned an error: %v", err)
}
}