optional API path prefix

This commit is contained in:
breel
2020-08-28 15:28:47 -06:00
parent 25a43c8a0b
commit ec5223d530
10 changed files with 160 additions and 27 deletions

View File

@@ -1,13 +1,19 @@
package auth
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"local/dndex/storage"
"local/dndex/storage/entity"
"net/http"
"github.com/google/uuid"
"gopkg.in/mgo.v2/bson"
)
func GeneratePlain(g storage.RateLimitedGraph, r *http.Request) (string, error) {
@@ -47,7 +53,26 @@ func readRequestedNamespace(r *http.Request) string {
}
func readRequested(r *http.Request, key string) string {
return r.FormValue(key)
switch r.Header.Get("Content-Type") {
case "application/json":
b, _ := ioutil.ReadAll(r.Body)
r.Body = struct {
io.Reader
io.Closer
}{
Reader: bytes.NewReader(b),
Closer: r.Body,
}
m := bson.M{}
json.Unmarshal(b, &m)
v, ok := m[key]
if !ok {
return ""
}
return fmt.Sprint(v)
default:
return r.FormValue(key)
}
}
func getKeyForNamespace(ctx context.Context, g storage.RateLimitedGraph, namespace string) (string, error) {

View File

@@ -95,3 +95,30 @@ func TestGenerate(t *testing.T) {
}
})
}
func TestReadRequested(t *testing.T) {
t.Run("form: ignore query params", func(t *testing.T) {
r := httptest.NewRequest(http.MethodPost, "/a=c", nil)
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if got := readRequested(r, "a"); got != "" {
t.Fatal(got)
}
})
t.Run("form: body beats query params", func(t *testing.T) {
r := httptest.NewRequest(http.MethodPost, "/a=c", strings.NewReader(`a=b`))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if got := readRequested(r, "a"); got != "b" {
t.Fatal(got)
}
})
t.Run("json: OK", func(t *testing.T) {
r := httptest.NewRequest(http.MethodPost, "/a=c", strings.NewReader(`{"a": "b"}`))
r.Header.Set("Content-Type", "application/json")
if got := readRequested(r, "a"); got != "b" {
t.Fatal(got)
}
})
}