server now opens a web server on the specified addr/port
This commit is contained in:
parent
8b438b6f3e
commit
cd7bcd5d55
12
main.go
12
main.go
@ -111,6 +111,7 @@ func main() {
|
||||
fmt.Printf("check successful\n")
|
||||
|
||||
case "server":
|
||||
for {
|
||||
cfg, err := config.ReadConfig(*cfgpath, *debuglvl)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%s\n", err.Error())
|
||||
@ -118,7 +119,16 @@ func main() {
|
||||
}
|
||||
|
||||
srv := server.NewServer(cfg, *debuglvl)
|
||||
srv.Start()
|
||||
|
||||
r, err := srv.Start()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%s\n", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
if !r {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case "help", "":
|
||||
printUsage()
|
||||
|
19
server/http.go
Normal file
19
server/http.go
Normal file
@ -0,0 +1,19 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/shutdown":
|
||||
fmt.Fprintf(w, "shutting down .. ")
|
||||
s.shutdownc <- false
|
||||
case "/restart":
|
||||
fmt.Fprintf(w, "restarting .. ")
|
||||
s.shutdownc <- true
|
||||
default:
|
||||
fmt.Fprintf(w, "Hello, world!")
|
||||
}
|
||||
}
|
@ -1,22 +1,35 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"git.binarythought.com/cdramey/alrm/config"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
workers []*worker
|
||||
cfg *config.Config
|
||||
shutdownc chan bool
|
||||
debuglvl int
|
||||
http http.Server
|
||||
}
|
||||
|
||||
func (srv *Server) Start() {
|
||||
func (srv *Server) Start() (bool, error) {
|
||||
listen, err := net.Listen("tcp", srv.cfg.Listen)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
for _, w := range srv.workers {
|
||||
go w.start()
|
||||
}
|
||||
|
||||
srv.http = http.Server{Handler: srv}
|
||||
go srv.http.Serve(listen)
|
||||
|
||||
t := time.NewTicker(srv.cfg.Interval)
|
||||
defer t.Stop()
|
||||
for {
|
||||
@ -28,14 +41,26 @@ func (srv *Server) Start() {
|
||||
for _, w := range srv.workers {
|
||||
w.wake()
|
||||
}
|
||||
case b := <-srv.shutdownc:
|
||||
srv.http.Shutdown(context.Background())
|
||||
for _, w := range srv.workers {
|
||||
w.shutdown()
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func NewServer(cfg *config.Config, debuglvl int) *Server {
|
||||
srv := &Server{cfg: cfg, debuglvl: debuglvl}
|
||||
srv := &Server{
|
||||
cfg: cfg,
|
||||
debuglvl: debuglvl,
|
||||
shutdownc: make(chan bool, 1),
|
||||
}
|
||||
for _, g := range cfg.Groups {
|
||||
srv.workers = append(srv.workers, makeworker(g, debuglvl))
|
||||
srv.workers = append(
|
||||
srv.workers, makeworker(g, debuglvl),
|
||||
)
|
||||
}
|
||||
return srv
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user