-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
103 lines (84 loc) · 2.16 KB
/
main.go
File metadata and controls
103 lines (84 loc) · 2.16 KB
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
102
103
package main
import (
"flag"
"io"
"net/http"
"net/url"
"os"
"regexp"
"github.com/schoeu/webhooks/config"
"github.com/schoeu/webhooks/routers"
"github.com/schoeu/webhooks/utils"
)
const (
defaultConfPath = ".webhook.conf"
defaultPort = "8910"
)
func main() {
var filePath, helper, port, command, token string
flag.StringVar(&filePath, "path", defaultConfPath, "path of config file.")
flag.StringVar(&port, "port", defaultPort, "server port.")
flag.StringVar(&helper, "help", "", "help")
flag.StringVar(&command, "add", "", "add router and command.")
flag.StringVar(&token, "token", "", "token for request")
flag.Parse()
// Usage like this: webhook --add "some_router:echo test_string"
// then request `localhost:8910/some_router` to run the command `echo test_string`
// Get config instance.
c := config.InitConfig(filePath)
// Add restart command to refresh configuration
args := os.Args
if len(args) > 1 && args[1] == "restart" {
c.Refresh()
return
}
router(c, token)
if command == "" {
// Get command from configuration.
c.Refresh()
http.ListenAndServe(":"+port, nil)
} else {
cmd, para := utils.Analysis(command)
if cmd != "" && para != "" {
c.Set(cmd, para)
}
}
}
// Router for actions.
func router(cf config.ConfigMap, token string) {
urlReg := regexp.MustCompile("/tasks/(\\w+)$")
cmdReg := regexp.MustCompile("/run/(.+)$")
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
c := utils.Context{}
c.Request = r
c.Writer = w
u, err := url.ParseQuery(r.URL.RawQuery)
utils.ErrHadle(err)
c.Query = u
path := r.URL.Path
if path == "/" {
io.WriteString(w, "Server is ready.")
return
}
// Token check.
if token != "" {
if u.Get("token") != token {
io.WriteString(w, "Wrong token.")
return
}
}
runInfo := cmdReg.FindAllStringSubmatch(path, -1)
taskInfo := urlReg.FindAllStringSubmatch(path, -1)
hit := false
if len(runInfo) > 0 && len(runInfo[0]) > 0 {
routers.RunRouter(c, runInfo)
return
}
if len(taskInfo) > 0 && len(taskInfo[0]) > 0 {
hit = routers.TaskRouter(c, taskInfo, cf)
}
if !hit {
io.WriteString(w, "No action for this router")
}
})
}