♻️ Move transformer to an isolated module
All checks were successful
release-nightly / build-docker (push) Successful in 1m3s

This commit is contained in:
2023-12-16 10:25:49 +08:00
parent ed1b20873d
commit ae165e0f12
4 changed files with 45 additions and 31 deletions

View File

@ -0,0 +1,56 @@
package transformers
import (
"encoding/json"
"github.com/gofiber/fiber/v2"
)
// Definitions
type RequestTransformer struct {
ModifyRequest func(options any, ctx *fiber.Ctx)
ModifyResponse func(options any, ctx *fiber.Ctx)
}
type RequestTransformerConfig struct {
Type string `json:"type" yaml:"type"`
Options any `json:"options" yaml:"options"`
}
func (v *RequestTransformerConfig) TransformRequest(ctx *fiber.Ctx) {
for k, f := range Transformers {
if k == v.Type {
if f.ModifyRequest != nil {
f.ModifyRequest(v.Options, ctx)
}
break
}
}
}
func (v *RequestTransformerConfig) TransformResponse(ctx *fiber.Ctx) {
for k, f := range Transformers {
if k == v.Type {
if f.ModifyResponse != nil {
f.ModifyResponse(v.Options, ctx)
}
break
}
}
}
// Helpers
func DeserializeOptions[T any](data any) T {
var out T
raw, _ := json.Marshal(data)
_ = json.Unmarshal(raw, &out)
return out
}
// Map of Transformers
// Every transformer need to be mapped here so that they can get work.
var Transformers = map[string]RequestTransformer{
"replacePath": ReplacePath,
}

View File

@ -0,0 +1,24 @@
package transformers
import (
"github.com/gofiber/fiber/v2"
"regexp"
"strings"
)
var ReplacePath = RequestTransformer{
ModifyRequest: func(options any, ctx *fiber.Ctx) {
opts := DeserializeOptions[struct {
Pattern string `json:"pattern"`
Value string `json:"value"`
Repl string `json:"repl"` // Use when complex mode(regexp) enabled
Complex bool `json:"complex"`
}](options)
path := string(ctx.Request().URI().Path())
if !opts.Complex {
ctx.Path(strings.ReplaceAll(path, opts.Pattern, opts.Value))
} else if ex := regexp.MustCompile(opts.Pattern); ex != nil {
ctx.Path(ex.ReplaceAllString(path, opts.Repl))
}
},
}