forked from djosephsen/lazlo
/
httpserver.go
83 lines (72 loc) · 2.08 KB
/
httpserver.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
package lib
import (
"fmt"
"net/http"
"github.com/bmizerany/pat"
)
//This map is redundant with the brokers callbacks.Index but there's
//no way to get a reference to the broker into metaHandler so kludge
var httpRoutes = make(map[string]*LinkCallback)
type LinkCallback struct {
p string // the httpRoutes index value
ID string
Path string // the computed URL
URL string
Handler func(res http.ResponseWriter, req *http.Request)
Chan chan *http.Request
}
func (b *Broker) StartHttp() {
m := pat.New()
m.Get("/", http.HandlerFunc(metaHandler))
m.Get("/linkcb/:name", http.HandlerFunc(metaHandler))
http.Handle("/", m)
err := http.ListenAndServe(":"+b.Config.Port, nil)
if err != nil {
Logger.Error(err)
}
}
func metaHandler(res http.ResponseWriter, req *http.Request) {
Logger.Debug("entered metaHandler")
path := req.URL.Query().Get(":name")
if path == `` {
Logger.Debug("path is /")
fmt.Fprintln(res, "Hi. I am a Lazlo bot")
} else if cb, ok := httpRoutes[path]; ok {
Logger.Debug("path is known")
if cb.Handler == nil {
go func(cb *LinkCallback) {
cb.Chan <- req
fmt.Fprintln(res, "Path: %s handled. Thanks!", path)
}(cb)
} else {
cb.Handler(res, req)
}
} else {
Logger.Debug("path is unknown (", path, ")")
fmt.Fprintf(res, "sorry, no modules have registered to handle %s\n", path)
}
}
func (b *Broker) LinkCallback(p string, f ...func(http.ResponseWriter, *http.Request)) *LinkCallback {
path := fmt.Sprintf("linkcb/%s", p)
callback := &LinkCallback{
p: p,
ID: fmt.Sprintf("link:%d", len(b.callbacks[L].Index)),
Path: path,
URL: fmt.Sprintf("%s:%s/%s", b.Config.URL, b.Config.Port, path),
Chan: make(chan *http.Request),
}
//user-provided http handler function
if f != nil {
callback.Handler = f[0]
}
//append the path to the list of routes used by metaHandler()
httpRoutes[p] = callback
if err := b.RegisterCallback(callback); err != nil {
Logger.Error("error registering callback ", callback.ID, ":: ", err)
return nil
}
return callback
}
func (l *LinkCallback) Delete() {
delete(httpRoutes, l.p)
}