From 5699171a30e6d91427ca8348157ee50b284d983e Mon Sep 17 00:00:00 2001 From: Zhang Minghan Date: Sun, 1 Oct 2023 19:22:37 +0800 Subject: [PATCH] add esm and unpkg proxy --- main.go | 3 +++ packages/custom.go | 27 +++++++++++++++++++++++++++ packages/esm.go | 23 +++++++++++++++++++++++ packages/unpkg.go | 23 +++++++++++++++++++++++ 4 files changed, 76 insertions(+) create mode 100644 packages/custom.go create mode 100644 packages/esm.go create mode 100644 packages/unpkg.go diff --git a/main.go b/main.go index a8eac10..fe7d0f0 100644 --- a/main.go +++ b/main.go @@ -26,6 +26,9 @@ func main() { { packages.RegisterJsdelivr(app) packages.RegisterFonts(app) + packages.RegisterEsm(app) + packages.RegisterUnpkg(app) + packages.RegisterCustom(app) } if err := app.Listen(fmt.Sprintf(":%d", viper.GetInt("port"))); err != nil { diff --git a/packages/custom.go b/packages/custom.go new file mode 100644 index 0000000..2a369e8 --- /dev/null +++ b/packages/custom.go @@ -0,0 +1,27 @@ +package packages + +import ( + "fmt" + "github.com/gofiber/fiber/v2" + "proxy/utils" + "strings" +) + +var CustomReplacer = map[string]string{ + "chatnio": "https://chatnio.net", +} + +func RegisterCustom(app *fiber.App) { + for _, v := range CustomReplacer { + app.All(fmt.Sprintf("/%s/*", v), func(c *fiber.Ctx) error { + source := strings.TrimPrefix(c.Path(), fmt.Sprintf("/%s", v)) + uri := fmt.Sprintf("%s%s", v, source) + data, err := utils.Get(uri, nil) + if err != nil { + return c.SendString(fmt.Sprintf("error during get data: %s", err.Error())) + } + + return c.SendString(data) + }) + } +} diff --git a/packages/esm.go b/packages/esm.go new file mode 100644 index 0000000..a142996 --- /dev/null +++ b/packages/esm.go @@ -0,0 +1,23 @@ +package packages + +import ( + "fmt" + "github.com/gofiber/fiber/v2" + "proxy/utils" + "strings" +) + +func RegisterEsm(app *fiber.App) { + app.All("/esm/*", func(c *fiber.Ctx) error { + source := strings.TrimPrefix(c.Path(), "/esm") + uri := fmt.Sprintf("https://cdn.jsdelivr.net/npm%s", source) + data, err := utils.Get(uri, nil) + if err != nil { + return c.SendString(fmt.Sprintf("error during get data: %s", err.Error())) + } + + data = strings.Replace(data, "https://esm.sh", "/esm", -1) + + return c.SendString(data) + }) +} diff --git a/packages/unpkg.go b/packages/unpkg.go new file mode 100644 index 0000000..34a21c1 --- /dev/null +++ b/packages/unpkg.go @@ -0,0 +1,23 @@ +package packages + +import ( + "fmt" + "github.com/gofiber/fiber/v2" + "proxy/utils" + "strings" +) + +func RegisterUnpkg(app *fiber.App) { + app.All("/unpkg/*", func(c *fiber.Ctx) error { + source := strings.TrimPrefix(c.Path(), "/unpkg") + uri := fmt.Sprintf("https://unpkg.com%s", source) + data, err := utils.Get(uri, nil) + if err != nil { + return c.SendString(fmt.Sprintf("error during get data: %s", err.Error())) + } + + data = strings.Replace(data, "https://unpkg.com", "/unpkg", -1) + + return c.SendString(data) + }) +}