-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdeploy42.go
87 lines (71 loc) · 2.31 KB
/
deploy42.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
package deploy42
import (
"fmt"
"github.com/andrerocker/deploy42/command"
"github.com/andrerocker/deploy42/config"
"github.com/andrerocker/deploy42/util"
"github.com/gin-gonic/gin"
"io"
"strings"
)
type Engine struct {
http *gin.Engine
config config.Configuration
filters map[string]gin.HandlerFunc
}
func New(configFile string) Engine {
return Engine{gin.Default(), config.New(configFile), make(map[string]gin.HandlerFunc)}
}
func (self Engine) Chaining(name string, filter gin.HandlerFunc) {
self.filters[name] = filter
}
func (self Engine) Draw() {
for _, namespace := range self.config.Namespaces {
for groupName, commands := range namespace.Commands {
for _, verbs := range commands {
for verb, command := range verbs {
route := self.formattedEndpoint(namespace, groupName)
handlers := self.wrapValuesHandler(namespace, groupName, command.(string))
self.http.Handle(strings.ToUpper(verb), route, handlers...)
}
}
}
}
}
func (self Engine) Start() {
daemon := self.config.Daemon
listen := daemon.BindUrl()
self.http.Run(listen)
}
func (self Engine) wrapValuesHandler(namespace config.Namespace, groupName, commandTemplate string) []gin.HandlerFunc {
filters := self.resolveNamespaceFilters(namespace)
return append(filters, func(context *gin.Context) {
reader := self.resolveReader(context)
target := fmt.Sprintf("{%s}", groupName)
content := context.Params.ByName(groupName)
compiled := strings.Replace(commandTemplate, target, content, -1)
command.ExecuteCommand(reader, util.Flushed(context.Writer), compiled)
})
}
func (self Engine) formattedEndpoint(namespace config.Namespace, groupName string) string {
if self.config.Daemon.Http.Vars {
return fmt.Sprintf("/%s/%s/*%s", namespace.Endpoint, groupName, groupName)
}
return fmt.Sprintf("/%s/%s", namespace.Endpoint, groupName)
}
func (self Engine) resolveReader(context *gin.Context) io.Reader {
if self.config.Daemon.Http.Pipe {
return context.Request.Body
}
return strings.NewReader("")
}
func (self Engine) resolveNamespaceFilters(namespace config.Namespace) []gin.HandlerFunc {
filters := make([]gin.HandlerFunc, 0)
for _, filterName := range namespace.Chaining {
currentFilter := self.filters[filterName]
if currentFilter != nil {
filters = append(filters, currentFilter)
}
}
return filters
}