-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpd.go
50 lines (43 loc) · 1.3 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
package main
import (
"fmt"
"net/http"
"syscall"
)
const portMaxNum = 65535
// Httpd struct expressses http server that listen in Port and trigger Callback
type Httpd struct {
Port uint
Prefix string
Callback func(sig syscall.Signal) error
}
// NewHttpd creates new httpd instance with option
func NewHttpd(port uint, prefix string, callback func(sig syscall.Signal) error) (*Httpd, error) {
if port > portMaxNum {
return nil, fmt.Errorf("port number shold be smaller than %d", portMaxNum)
}
return &Httpd{
Port: port,
Prefix: prefix,
Callback: callback,
}, nil
}
// Run function starts http server
// http server handle signal-path generated by metadata of signals in signal.go
func (httpd *Httpd) Run() {
for i := 0; i < len(Signals); i++ {
signal := Signals[i]
signalStr := SignalStrs[i]
http.HandleFunc(httpd.Prefix+"/"+signalStr, func(w http.ResponseWriter, r *http.Request) {
err := httpd.Callback(signal)
if err != nil {
// If failed to process Callback, http server returns 500
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "Failed to poroxy %s to destination command", signalStr)
} else {
fmt.Fprintf(w, "Successed to proxy %s to destination command", signalStr)
}
})
}
http.ListenAndServe(fmt.Sprintf(":%d", httpd.Port), nil)
}