Skip to content

Commit

Permalink
Merge pull request #111 from flanksource/fix-postgrest-forward
Browse files Browse the repository at this point in the history
fix: postgrest forward traffic
  • Loading branch information
Kaitou786 authored Nov 10, 2022
2 parents 3e2cb50 + f3957dd commit ddfbafd
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 17 deletions.
35 changes: 18 additions & 17 deletions cmd/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,31 +28,15 @@ var Serve = &cobra.Command{
db.HTTPEndpoint = publicEndpoint + "/db"
go db.StartPostgrest()

url, err := url.Parse("http://localhost:3000")
if err != nil {
e.Logger.Fatal(err)
}

if logger.IsTraceEnabled() {
e.Use(middleware.Logger())
}

forward(e, "/db", db.PostgRESTEndpoint())
e.GET("/health", func(c echo.Context) error {
return c.String(http.StatusOK, "OK")
})
e.GET("/query", query.Handler)

e.Group("/db").Use(middleware.ProxyWithConfig(middleware.ProxyConfig{
Rewrite: map[string]string{
"^/db/*": "/$1",
},
Balancer: middleware.NewRoundRobinBalancer([]*middleware.ProxyTarget{
{
URL: url,
},
}),
}))

// Run this in a goroutine to make it non-blocking for server start
go startScraperCron(args)

Expand Down Expand Up @@ -95,6 +79,23 @@ func startScraperCron(configFiles []string) {

}

func forward(e *echo.Echo, prefix string, target string) {
targetURL, err := url.Parse(target)
if err != nil {
e.Logger.Fatal(err)
}
e.Group(prefix).Use(middleware.ProxyWithConfig(middleware.ProxyConfig{
Rewrite: map[string]string{
fmt.Sprintf("^%s/*", prefix): "/$1",
},
Balancer: middleware.NewRoundRobinBalancer([]*middleware.ProxyTarget{
{
URL: targetURL,
},
}),
}))
}

func init() {
ServerFlags(Serve.Flags())
}
10 changes: 10 additions & 0 deletions db/postgrest.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
package db

import (
"fmt"
"strconv"

"github.com/flanksource/commons/deps"
"github.com/flanksource/commons/logger"
)

// PostgRESTVersion ...
var PostgRESTVersion = "v9.0.0"

var PostgRESTServerPort = 3000

func PostgRESTEndpoint() string {
return fmt.Sprintf("http://localhost:%d", PostgRESTServerPort)
}

// GoOffline ...
func GoOffline() error {
return getBinary()("--help")
Expand All @@ -19,6 +28,7 @@ func getBinary() deps.BinaryFunc {
"PGRST_DB_SCHEMA": Schema,
"PGRST_DB_ANON_ROLE": "postgrest_api",
"PGRST_OPENAPI_SERVER_PROXY_URI": HTTPEndpoint,
"PGRST_DB_PORT": strconv.Itoa(PostgRESTServerPort),
"PGRST_LOG_LEVEL": LogLevel,
})
}
Expand Down

0 comments on commit ddfbafd

Please sign in to comment.