Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions api/archive.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package api

import (
"math/rand"
"net/http"
"net/http/httputil"
"net/url"

"api.audius.co/config"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/adaptor"
)

func archiveProxy(c *fiber.Ctx) error {
// Handle preflight
if c.Method() == fiber.MethodOptions {
c.Response().Header.Set("Access-Control-Allow-Origin", "*")
c.Response().Header.Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
c.Response().Header.Set("Access-Control-Allow-Headers", "*")
return c.Status(fiber.StatusNoContent).Send(nil)
}
randIdx := rand.Intn(len(config.Cfg.ArchiverNodes))
upstream, _ := url.Parse(config.Cfg.ArchiverNodes[randIdx])
proxy := httputil.NewSingleHostReverseProxy(upstream)
proxy.Director = func(req *http.Request) {
req.URL.Scheme = upstream.Scheme
req.URL.Host = upstream.Host
req.Host = upstream.Host
}
proxy.ModifyResponse = func(resp *http.Response) error {
resp.Header.Del("Access-Control-Allow-Origin")
return nil
}
c.Set("Access-Control-Allow-Origin", "*")
return adaptor.HTTPHandler(proxy)(c)
}
31 changes: 6 additions & 25 deletions api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,8 @@ import (
"context"
_ "embed"
"fmt"
"math/rand"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/signal"
"reflect"
Expand Down Expand Up @@ -305,6 +302,12 @@ func NewApiServer(config config.Config) *ApiServer {
return c.JSON(app.metricsCollector.Debug())
})

// Unsplash proxy
app.All("/unsplash/*", app.unsplash)

// Archiver proxy
app.All("/archive/*", archiveProxy)

// resolve myId
app.Use(app.isFullMiddleware)
app.Use(app.resolveMyIdMiddleware)
Expand Down Expand Up @@ -595,28 +598,6 @@ func NewApiServer(config config.Config) *ApiServer {
app.Get("/content/verbose", app.contentNodes)
app.Get("/content-nodes/verbose", app.contentNodes)

// Unsplash proxy
app.All("/unsplash/*", app.unsplash)

// Archiver proxy
if len(config.ArchiverNodes) > 0 {
app.All("/archive/*", func(c *fiber.Ctx) error {
randIdx := rand.Intn(len(config.ArchiverNodes))
upstreamUrl := config.ArchiverNodes[randIdx]
upstream, err := url.Parse(upstreamUrl)
if err != nil {
return fiber.NewError(fiber.StatusBadGateway, "Invalid Archiver upstream url")
}
proxy := httputil.NewSingleHostReverseProxy(upstream)
origDirector := proxy.Director
proxy.Director = func(req *http.Request) {
origDirector(req)
req.Host = upstream.Host
}
return adaptor.HTTPHandler(proxy)(c)
})
}

app.Static("/", "./static")

// Disable swagger in test environments, because it will slow things down a lot
Expand Down