72 lines
1.7 KiB
Go
72 lines
1.7 KiB
Go
package prog
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"encoding/xml"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
func CreateAndStartHTTPServer(conf *Configuration) *http.Server {
|
|
router := http.NewServeMux()
|
|
router.HandleFunc("/processes", AreProcessesUp(&conf.Processes))
|
|
|
|
srv := &http.Server{
|
|
Addr: conf.ListenAddress,
|
|
Handler: router,
|
|
ReadTimeout: 5 * time.Second,
|
|
WriteTimeout: 5 * time.Second,
|
|
IdleTimeout: 10 * time.Second,
|
|
}
|
|
|
|
go func() {
|
|
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
|
log.Fatalf("ListenAndServe: %s\n", err)
|
|
}
|
|
}()
|
|
|
|
return srv
|
|
}
|
|
|
|
func ShutdownHTTPServer(srv *http.Server) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
|
|
srv.SetKeepAlivesEnabled(false)
|
|
if err := srv.Shutdown(ctx); err != nil {
|
|
log.Fatalf("%s\n", err)
|
|
}
|
|
}
|
|
|
|
// AreProcessesUp handles a GET /processes request and sends back status of given
|
|
// processes.
|
|
func AreProcessesUp(processes *[]string) func(http.ResponseWriter, *http.Request) {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == http.MethodGet {
|
|
proclist := NewProcessList()
|
|
|
|
for _, proc := range *processes {
|
|
isup, _, _ := IsProcessUp(proc)
|
|
proclist.AddProcess(proc, isup)
|
|
}
|
|
|
|
if hdr := r.Header.Get("Accept"); hdr == "application/xml" {
|
|
w.Header().Add("Content-Type", "application/xml")
|
|
enc := xml.NewEncoder(w)
|
|
enc.Indent("", "\t")
|
|
enc.Encode(proclist)
|
|
} else {
|
|
w.Header().Add("Content-Type", "application/json")
|
|
enc := json.NewEncoder(w)
|
|
enc.SetIndent("", "\t")
|
|
enc.Encode(proclist)
|
|
}
|
|
} else {
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
|
w.Header().Add("Allow", "GET")
|
|
}
|
|
}
|
|
}
|