-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
19 changed files
with
600 additions
and
201 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -16,3 +16,4 @@ | |
dist | ||
.idea | ||
.env | ||
.vscode/settings.json |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.