1
0
mirror of https://github.com/nxshock/gron.git synced 2024-11-27 03:41:00 +05:00
gron/httpserver.go

94 lines
2.1 KiB
Go
Raw Normal View History

2022-03-26 13:23:39 +05:00
package main
import (
"bytes"
"fmt"
"net/http"
2022-03-26 16:44:46 +05:00
"os"
2022-03-26 13:23:39 +05:00
"time"
log "github.com/sirupsen/logrus"
)
func httpServer(listenAddress string) {
http.HandleFunc("/", handler)
2022-03-26 20:20:00 +05:00
http.HandleFunc("/reloadJobs", handleReloadJobs)
2022-03-26 16:44:46 +05:00
http.HandleFunc("/shutdown", handleShutdown)
2022-03-26 13:23:39 +05:00
http.HandleFunc("/start", handleForceStart)
log.WithField("job", "http_server").Fatal(http.ListenAndServe(listenAddress, nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
if r.RequestURI != "/" {
http.Error(w, "", http.StatusNotFound)
return
}
2022-03-26 20:20:00 +05:00
globalMutex.RLock()
2022-03-26 13:23:39 +05:00
buf := new(bytes.Buffer)
jobEntries := c.Entries()
var jobs []*Job
for _, v := range jobEntries {
jobs = append(jobs, v.Job.(*Job))
}
indexTemplate.ExecuteTemplate(buf, "index", jobs)
2022-03-26 20:20:00 +05:00
globalMutex.RUnlock()
2022-03-26 13:23:39 +05:00
buf.WriteTo(w)
}
func handleForceStart(w http.ResponseWriter, r *http.Request) {
jobName := r.FormValue("jobName")
if jobName == "" {
http.Error(w, "job name is not specified", http.StatusBadRequest)
return
}
jobEntries := c.Entries()
for _, jobEntry := range jobEntries {
job := jobEntry.Job.(*Job)
if job.FileName == jobName {
log.WithField("job", "http_server").Printf("forced start %s", job.FileName)
go job.Run()
time.Sleep(time.Second / 4) // wait some time for job start
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
}
http.Error(w, fmt.Sprintf("there is no job with name %s", jobName), http.StatusBadRequest)
}
2022-03-26 16:44:46 +05:00
func handleShutdown(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Application terminated.\n"))
go func() {
time.Sleep(time.Second)
log.WithField("job", "http_server").Infoln("Shutdown requested")
os.Exit(0)
}()
}
2022-03-26 20:20:00 +05:00
func handleReloadJobs(w http.ResponseWriter, r *http.Request) {
globalMutex.Lock()
defer globalMutex.Unlock()
c.Stop()
for _, entry := range c.Entries() {
c.Remove(entry.ID)
}
err := initJobs()
if err != nil {
http.Error(w, fmt.Sprintf("reload jobs error: %v", err), http.StatusInternalServerError)
return
}
c.Start()
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
}