2020-04-01 02:08:21 +00:00
|
|
|
package main
|
|
|
|
|
2020-04-06 22:17:07 +00:00
|
|
|
import (
|
|
|
|
"github.com/spf13/viper"
|
|
|
|
"regexp"
|
|
|
|
)
|
2020-04-01 02:08:21 +00:00
|
|
|
|
|
|
|
const (
|
2020-04-06 22:17:07 +00:00
|
|
|
rulesConfigKey = "rules"
|
|
|
|
patternConfigKey = "pattern"
|
|
|
|
responseConfigKey = "response"
|
2020-04-01 02:08:21 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type targetRule struct {
|
2020-04-06 22:17:07 +00:00
|
|
|
pattern *regexp.Regexp
|
|
|
|
response string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (tr targetRule) Pattern() *regexp.Regexp {
|
|
|
|
return tr.pattern
|
|
|
|
}
|
|
|
|
|
|
|
|
func (tr targetRule) Response() string {
|
|
|
|
return tr.response
|
2020-04-01 02:08:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type httpOptions struct {
|
|
|
|
Rules []targetRule
|
|
|
|
}
|
|
|
|
|
2020-04-12 01:51:41 +00:00
|
|
|
func loadFromConfig(config *viper.Viper) (options httpOptions) {
|
2020-04-01 02:08:21 +00:00
|
|
|
anonRules := config.Get(rulesConfigKey).([]interface{})
|
|
|
|
|
|
|
|
for _, i := range anonRules {
|
|
|
|
innerData := i.(map[interface{}]interface{})
|
2020-04-06 22:17:07 +00:00
|
|
|
|
|
|
|
if rulePattern, err := regexp.Compile(innerData[patternConfigKey].(string)); err == nil {
|
|
|
|
options.Rules = append(options.Rules, targetRule{
|
|
|
|
pattern: rulePattern,
|
|
|
|
response: innerData[responseConfigKey].(string),
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
panic(err)
|
|
|
|
}
|
2020-04-01 02:08:21 +00:00
|
|
|
}
|
|
|
|
|
2020-04-12 01:51:41 +00:00
|
|
|
return
|
2020-04-01 02:08:21 +00:00
|
|
|
}
|