Skip to content

Commit

Permalink
add config support
Browse files Browse the repository at this point in the history
  • Loading branch information
elonzh committed Nov 2, 2020
1 parent 7eb0178 commit 9dc5a92
Show file tree
Hide file tree
Showing 19 changed files with 600 additions and 201 deletions.
7 changes: 7 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[flake8]
extend-ignore = E203, E266, E501
# line length is intentionally set to 80 here because black uses Bugbear
# See https://github.com/psf/black/blob/master/docs/the_black_code_style.md#line-length for more details
max-line-length = 80
max-complexity = 18
select = B,C,E,F,W,T4,B9
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@
dist
.idea
.env
.vscode/settings.json
2 changes: 1 addition & 1 deletion .goreleaser.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ builds:
- windows
goarch:
- amd64
main: ./cmd/trumpet/main.go
main: ./main.go

archives:
- format_overrides:
Expand Down
4 changes: 2 additions & 2 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/cmd/trumpet/main.go",
"program": "${workspaceFolder}/main.go",
"env": {},
"args": [],
"args": ["--logLevel", "debug", "serve"],
"output": "${workspaceFolder}/dist/trumpet"
}
]
Expand Down
8 changes: 6 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
FROM alpine
ENTRYPOINT ["/bin/trumpet"]
COPY trumpet /bin/trumpet
ENV GIN_MODE=release
RUN mkdir /app
WORKDIR /app
ENTRYPOINT [ "/app/trumpet" ]
CMD [ "serve" ]
COPY trumpet /app/trumpet
12 changes: 6 additions & 6 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License
The MIT License (MIT)

Copyright (c) 2020 elonzh
Copyright © 2020 elonzh

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand All @@ -9,13 +9,13 @@ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
91 changes: 91 additions & 0 deletions cmd/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
Copyright © 2020 elonzh <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cmd

import (
"github.com/elonzh/trumpet/transformers"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

// configCmd represents the config command
var configCmd = &cobra.Command{
Use: "config",
Short: "",
Long: ``,
}

type Config struct {
LogLevel logrus.Level
Transformers map[string]*transformers.Transformer
}

var (
cfg = &Config{
LogLevel: logrus.InfoLevel,
Transformers: map[string]*transformers.Transformer{},
}
)

func registerTransformers(m map[string]string) {
for name, src := range m {
t, err := transformers.NewTransformer(name, src)
if err != nil {
logrus.WithError(err).WithField("Name", name).Fatalln("error when init Transformer")
}
if _, exists := cfg.Transformers[t.Name]; exists {
logrus.WithField("Name", name).Warnln("Transformer already exists")
}
cfg.Transformers[t.Name] = t
}
}

func init() {
builtinTransformers := map[string]string{
"feishu-to-dingtalk": `
def transform(raw):
origin_body = json.decode(raw)
msg_type = origin_body['msg_type']
body = {}
if msg_type == "text":
body = {"msgtype": "text", "text": {"content": origin_body["content"]["text"]}}
return json.encode(body)
`,
"dingtalk-to-feishu": `
def transform(raw):
origin_body = json.decode(raw)
msg_type = origin_body['msgtype']
body = {}
if msg_type == "text":
body = {"msg_type": "text", "content": {"text": origin_body["text"]["content"]}}
elif msg_type == "markdown":
title = origin_body["markdown"].get("title")
text = origin_body["markdown"].get("text", "")
if title:
text = title + "\n" + text
body = {"msg_type": "text", "content": {"text": text}}
return json.encode(body)
`,
}
registerTransformers(builtinTransformers)
rootCmd.AddCommand(configCmd)
}
79 changes: 79 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
Copyright © 2020 elonzh
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cmd

import (
"os"

"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var cfgFile string

var rootCmd = &cobra.Command{
Use: "trumpet",
Short: "🎺simple webhook transform server",
Long: ``,
}

func Execute() {
if err := rootCmd.Execute(); err != nil {
logrus.WithError(err).Fatalln()
}
}

func init() {
cobra.OnInitialize(initConfig)

rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file (default is ./config.yaml)")
rootCmd.PersistentFlags().String("logLevel", "info", "")
err := viper.BindPFlag("logLevel", rootCmd.PersistentFlags().Lookup("logLevel"))
if err != nil {
panic(err)
}
}

func initConfig() {
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
} else {
viper.AddConfigPath(".")
viper.SetConfigName("config")
}
var err error
if err = viper.ReadInConfig(); os.IsNotExist(err) {
logrus.WithError(err).Fatalln()
}
logrus.WithField("ConfigFile", viper.ConfigFileUsed()).Infoln("read in config")
cfg.LogLevel, err = logrus.ParseLevel(viper.GetString("logLevel"))
if err != nil {
logrus.WithError(err).Fatalln()
}
logrus.SetLevel(cfg.LogLevel)
if cfg.LogLevel >= logrus.DebugLevel {
logrus.WithField("Config", cfg).Debug()
}
logrus.SetFormatter(&logrus.TextFormatter{})
registerTransformers(viper.GetStringMapString("transformers"))
}
81 changes: 81 additions & 0 deletions cmd/serve.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package cmd

import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"strings"

"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

var serveCmd = &cobra.Command{
Use: "serve",
Short: "",
Long: ``,
RunE: func(cmd *cobra.Command, args []string) error {
r := gin.Default()
r.POST("/transformers/:transformer", func(c *gin.Context) {
transformerName := c.Param("transformer")
trumpetTo, err := url.Parse(c.Query("trumpet_to"))
if err != nil {
c.String(http.StatusBadRequest, err.Error())
return
}
transformer, ok := cfg.Transformers[transformerName]
if !ok {
c.String(http.StatusNotFound, "no such transformer `%s`", transformer)
return
}
raw, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
c.String(http.StatusBadRequest, err.Error())
return
}
rawBody, err := transformer.Exec(string(raw))
if err != nil {
c.String(http.StatusInternalServerError, "error when transform data: %s", err)
return
}
proxy := httputil.ReverseProxy{
Director: func(request *http.Request) {
request.Host = trumpetTo.Host
request.URL = trumpetTo
request.RequestURI = ""
request.Header["X-Forwarded-For"] = nil
request.ContentLength = -1
delete(request.Header, "Content-Length")

request.Body = ioutil.NopCloser(strings.NewReader(rawBody))
if cfg.LogLevel >= logrus.DebugLevel {
req, err := httputil.DumpRequest(request, true)
fmt.Printf(
"\n-------------------- Request --------------------\n%s\nDumpRequestError:%s\n",
req, err,
)
}
},
ModifyResponse: func(response *http.Response) error {
if cfg.LogLevel >= logrus.DebugLevel {
resp, err := httputil.DumpResponse(response, true)
fmt.Printf(
"\n-------------------- Request --------------------\n%s\nDumpResponseError:%s\n",
resp, err,
)
}
return nil
},
}
proxy.ServeHTTP(c.Writer, c.Request)
})
return r.Run()
},
}

func init() {
rootCmd.AddCommand(serveCmd)
}
73 changes: 0 additions & 73 deletions cmd/trumpet/main.go

This file was deleted.

Loading

0 comments on commit 9dc5a92

Please sign in to comment.