2022-01-02 02:56:46 +04:00
|
|
|
package prog
|
2021-12-24 23:28:50 +04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
|
|
|
"encoding/xml"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2022-01-02 02:56:46 +04:00
|
|
|
func CreateAndStartHTTPServer(conf *Configuration) *http.Server {
|
2021-12-24 23:28:50 +04:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2022-01-02 02:56:46 +04:00
|
|
|
func ShutdownHTTPServer(srv *http.Server) {
|
2021-12-24 23:28:50 +04:00
|
|
|
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")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|