-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathcontrol.go
101 lines (89 loc) · 2.47 KB
/
control.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Control offers an HTTP JSON API.
package main
import (
"fmt"
"net"
"net/http"
"github.com/mpdroog/radiusd/config"
"github.com/itshosted/webutils/httpd"
"github.com/itshosted/webutils/middleware"
"github.com/itshosted/webutils/muxdoc"
"github.com/itshosted/webutils/ratelimit"
)
var (
mux muxdoc.MuxDoc
ln net.Listener
)
func Control() {
mux.Title = "RadiusdD API"
mux.Desc = "Administrative API"
mux.Add("/", doc, "This documentation")
mux.Add("/shutdown", shutdown, "Finish jobs and close application")
mux.Add("/verbose", verbose, "Toggle verbosity-mode")
middleware.Add(ratelimit.Use(5, 5))
http.Handle("/", middleware.Use(mux.Mux))
var e error
server := &http.Server{Addr: config.C.ControlListen, Handler: nil}
ln, e = net.Listen("tcp", server.Addr)
if e != nil {
panic(e)
}
if config.Verbose {
config.Log.Printf("httpd listening on " + config.C.ControlListen)
}
if e := server.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)}); e != nil {
if !config.Stopping {
panic(e)
}
}
}
// Return API Documentation (paths)
func doc(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(404)
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(mux.String()))
}
// Finish pending jobs and close application
func shutdown(w http.ResponseWriter, r *http.Request) {
if config.Stopping {
if _, e := w.Write([]byte(fmt.Sprintf(`{"success": true, "msg": "Already stopping."}`))); e != nil {
config.Log.Printf("control: " + e.Error())
return
}
}
config.Log.Printf("Disconnecting")
config.Stopping = true
if e := ln.Close(); e != nil {
if _, e := w.Write([]byte(fmt.Sprintf(`{"success": false, "msg": "Error stopping HTTP-listener"}`))); e != nil {
config.Log.Printf("control: " + e.Error())
return
}
}
for _, sock := range config.Sock {
if e := sock.Close(); e != nil {
if _, e := w.Write([]byte(fmt.Sprintf(`{"success": false, "msg": "Error stopping listener"}`))); e != nil {
config.Log.Printf("control: " + e.Error())
return
}
}
}
if _, e := w.Write([]byte(`{"success": true, "msg": "Stopped listening, waiting for empty queue."}`)); e != nil {
config.Log.Printf("control: " + e.Error())
return
}
}
func verbose(w http.ResponseWriter, r *http.Request) {
msg := `{success: true, msg: "Set verbosity to `
if config.Verbose {
config.Verbose = false
msg += "OFF"
} else {
config.Verbose = true
msg += "ON"
}
msg += `"}`
if _, e := w.Write([]byte(msg)); e != nil {
httpd.Error(w, e, "Flush failed")
return
}
}