Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Router to runtime.Params #3458

Merged
merged 1 commit into from May 17, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions runtime/runtime.go
Expand Up @@ -21,6 +21,7 @@ import (
"time"

"github.com/fsnotify/fsnotify"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"go.uber.org/automaxprocs/maxprocs"
Expand Down Expand Up @@ -182,6 +183,11 @@ type Params struct {
// configured bundles and plugins to be activated/ready before listening for traffic.
// A value of 0 or less means no wait is exercised.
ReadyTimeout int

// Router is the router to which handlers for the REST API are added.
// Router uses a first-matching-route-wins strategy, so no existing routes are overridden
// If it is nil, a new mux.Router will be created
Router *mux.Router
}

// LoggingConfig stores the configuration for OPA's logging behaviour.
Expand Down Expand Up @@ -352,6 +358,7 @@ func (rt *Runtime) Serve(ctx context.Context) error {
defer rt.Manager.Stop(ctx)

rt.server = server.New().
WithRouter(rt.Params.Router).
WithStore(rt.Store).
WithManager(rt.Manager).
WithCompilerErrorLimit(rt.Params.ErrorLimit).
Expand Down
22 changes: 22 additions & 0 deletions server/server_test.go
Expand Up @@ -18,6 +18,7 @@ import (
"testing"
"time"

"github.com/gorilla/mux"
"github.com/pkg/errors"

"github.com/open-policy-agent/opa/ast"
Expand Down Expand Up @@ -3607,6 +3608,27 @@ func TestMixedAddrTypes(t *testing.T) {
}
}

func TestCustomRoute(t *testing.T) {
router := mux.NewRouter()
router.HandleFunc("/customEndpoint", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"myCustomResponse": true}`))
})
f := newFixture(t, func(server *Server) {
server.WithRouter(router)
})

if err := f.v1(http.MethodGet, "/data", "", 200, `{"result":{}}`); err != nil {
t.Fatalf("Unexpected response for default server route: %v", err)
}
r, err := http.NewRequest(http.MethodGet, "/customEndpoint", nil)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
if err := f.executeRequest(r, http.StatusOK, `{"myCustomResponse": true}`); err != nil {
t.Fatalf("Request to custom endpoint failed: %s", err)
}
}

func TestDiagnosticRoutes(t *testing.T) {
cases := []struct {
path string
Expand Down