/
httpd.go
85 lines (73 loc) · 1.77 KB
/
httpd.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
// Package httpd provides web service
package httpd
import (
"fmt"
"github.com/gorilla/mux"
"github.com/rakyll/statik/fs"
"net/http"
"github.com/mehrdadrad/mylg/cli"
// statik is single binary including all web stuff
_ "github.com/mehrdadrad/mylg/services/dashboard/statik"
)
type TTracker struct {
ch chan string
host string
}
// Route represents a HTTP route
type Route struct {
Name string
Method string
Path string
HandlerFunc http.HandlerFunc
}
// APIHandler represents API function w/ cli arg
type APIHandler func(w http.ResponseWriter, r *http.Request, cfg cli.Config)
var ttracker = make(map[int]TTracker)
// APIWrapper wraps API func including cli arg
func APIWrapper(handler APIHandler, cfg cli.Config) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
handler(w, r, cfg)
}
}
// API handles API routes
func API(w http.ResponseWriter, r *http.Request, cfg cli.Config) {
var f = mux.Vars(r)["name"]
w.Header().Set("Content-Type", "application/json")
switch f {
case "ping":
ping(w, r, &cfg)
case "init.trace":
initTrace(w, r, &cfg)
case "get.trace":
getTrace(w, r)
case "close.trace":
closeTrace(w, r)
case "geo":
getGeo(w, r)
}
}
// Run starts web service
func Run(cfg cli.Config) {
statikFS, _ := fs.New()
router := mux.NewRouter().StrictSlash(true)
routes := []Route{
{
"API",
"GET",
"/api/{name}",
APIWrapper(API, cfg),
},
}
for _, route := range routes {
router.
Path(route.Path).
Methods(route.Method).
Name(route.Name).
Handler(route.HandlerFunc)
}
router.PathPrefix("/").Handler(http.FileServer(statikFS))
err := http.ListenAndServe(fmt.Sprintf("%s:%d", cfg.Web.Address, cfg.Web.Port), router)
if err != nil {
println(err.Error())
}
}