Skip to content

Commit

Permalink
httptransport: made discovery endpoint more Accepting
Browse files Browse the repository at this point in the history
This makes the OpenAPI endpoint honor the splat MIME types.

Signed-off-by: Hank Donnay <hdonnay@redhat.com>
  • Loading branch information
hdonnay committed Sep 24, 2020
1 parent cd34ea9 commit e1144aa
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
15 changes: 10 additions & 5 deletions httptransport/discoveryhandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ import (

//go:generate go run openapigen.go

var okCT = map[string]string{
"application/vnd.oai.openapi+json": "application/vnd.oai.openapi+json",
"application/json": "application/json",
"application/*": "application/vnd.oai.openapi+json",
"*/*": "application/vnd.oai.openapi+json",
}

// DiscoveryHandler serves the embedded OpenAPI spec.
func DiscoveryHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand All @@ -20,15 +27,14 @@ func DiscoveryHandler() http.Handler {
je.Error(w, resp, http.StatusMethodNotAllowed)
return
}
ct := "application/vnd.oai.openapi+json"
w.Header().Set("content-type", okCT["*/*"])
// Add a gate so that requesters expecting the yaml version get some
// sort of error.
if as, ok := r.Header["Accept"]; ok {
bail := true
for _, a := range as {
if a == "application/json" ||
a == "application/vnd.oai.openapi+json" {
ct = a
if ct, ok := okCT[a]; ok {
w.Header().Set("content-type", ct)
bail = false
break
}
Expand All @@ -42,7 +48,6 @@ func DiscoveryHandler() http.Handler {
return
}
}
w.Header().Add("content-type", ct)
w.Header().Set("etag", _openapiJSONEtag)
var err error
defer writerError(w, &err)()
Expand Down
15 changes: 15 additions & 0 deletions httptransport/discoveryhandler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ func TestDiscoveryEndpoint(t *testing.T) {

r := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/openapi/v1", nil)
req.Header.Set("Accept", "application/json")
h.ServeHTTP(r, req)

resp := r.Result()
Expand All @@ -45,6 +46,20 @@ func TestDiscoveryEndpoint(t *testing.T) {
t.Logf("openapi verion: %v", m["openapi"])
}

func TestDiscoveryFailure(t *testing.T) {
h := DiscoveryHandler()

r := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/openapi/v1", nil)
req.Header.Set("Accept", "application/yaml")
h.ServeHTTP(r, req)

resp := r.Result()
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("got status code: %v want status code: %v", resp.StatusCode, http.StatusBadRequest)
}
}

func TestEmbedding(t *testing.T) {
ctx, done := context.WithCancel(context.Background())
defer done()
Expand Down

0 comments on commit e1144aa

Please sign in to comment.