feat: app
This commit is contained in:
100
server.go
Normal file
100
server.go
Normal file
@@ -0,0 +1,100 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
var database Database
|
||||
|
||||
type UpdateRequest struct {
|
||||
Name string `json:"name"`
|
||||
Healthy bool `json:"healthy"`
|
||||
}
|
||||
|
||||
func health(w http.ResponseWriter, req *http.Request) {
|
||||
if req.Method == "GET" {
|
||||
getHealth(w, req)
|
||||
} else if req.Method == "POST" {
|
||||
updateHealth(w, req)
|
||||
} else {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
func getHealth(w http.ResponseWriter, req *http.Request) {
|
||||
serviceId := req.URL.Query().Get("service")
|
||||
|
||||
if serviceId == "" {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write([]byte("Service parameter not supplied"))
|
||||
return
|
||||
}
|
||||
|
||||
service := database.Get(serviceId)
|
||||
|
||||
if service == nil {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
w.Write([]byte("Service not found with id " + serviceId))
|
||||
return
|
||||
}
|
||||
|
||||
response, err := json.Marshal(service)
|
||||
if err != nil {
|
||||
log.Fatalf("Error marshalling JSON response: %v", err)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write(response)
|
||||
}
|
||||
func updateHealth(w http.ResponseWriter, req *http.Request) error {
|
||||
var updateRequest UpdateRequest
|
||||
if req.Body == nil {
|
||||
http.Error(w, "Request has no body", http.StatusBadRequest)
|
||||
return errors.New("request has no body")
|
||||
}
|
||||
err := json.NewDecoder(req.Body).Decode(&updateRequest)
|
||||
if err != nil {
|
||||
http.Error(w, "Error while parsing request", http.StatusBadRequest)
|
||||
log.Default().Println(err)
|
||||
return err
|
||||
}
|
||||
|
||||
err = database.Update(Service{Name: updateRequest.Name, Healthy: updateRequest.Healthy})
|
||||
if err != nil {
|
||||
http.Error(w, "Error while updating service", 500)
|
||||
return err
|
||||
}
|
||||
|
||||
w.WriteHeader(200)
|
||||
return nil
|
||||
}
|
||||
|
||||
func status(w http.ResponseWriter, req *http.Request) {
|
||||
result, err := database.GetAllStatus()
|
||||
|
||||
if err != nil {
|
||||
http.Error(w, "Error while fetching status", 500)
|
||||
return
|
||||
}
|
||||
|
||||
response, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
log.Fatalf("Error marshalling JSON response: %v", err)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*") // URL of the Kea control agent API endpoint
|
||||
w.Write(response)
|
||||
}
|
||||
|
||||
func webServer(db Database) {
|
||||
database = db
|
||||
|
||||
http.HandleFunc("/health", health)
|
||||
http.HandleFunc("/status", status)
|
||||
|
||||
http.ListenAndServe(":8090", nil)
|
||||
}
|
||||
Reference in New Issue
Block a user