Skip to content

Commit

Permalink
http: support QueryUnescape in HTTPPool.ServeHTTP
Browse files Browse the repository at this point in the history
HTTPPool will inverse escaped path if query parameter contains
"escaped=true".

Add keys with char to be escaped in test.
  • Loading branch information
lorneli committed Nov 8, 2017
1 parent 84a468c commit e652685
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 8 deletions.
40 changes: 35 additions & 5 deletions http.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,18 +138,48 @@ func (p *HTTPPool) PickPeer(key string) (ProtoGetter, bool) {
return nil, false
}

func (p *HTTPPool) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Parse request.
func (p *HTTPPool) parseRequest(r *http.Request) (groupName, key string, ok bool) {
if !strings.HasPrefix(r.URL.Path, p.opts.BasePath) {
panic("HTTPPool serving unexpected path: " + r.URL.Path)
}
parts := strings.SplitN(r.URL.Path[len(p.opts.BasePath):], "/", 2)
if len(parts) != 2 {
return
}
groupName = parts[0]
key = parts[1]

queries, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
// Still accept groupName and key in path.
ok = true
return
}

var uerr error
if queries.Get("escaped") == "true" {
groupName, uerr = url.QueryUnescape(groupName)
if uerr != nil {
ok = false
return
}
key, uerr = url.QueryUnescape(key)
if uerr != nil {
ok = false
return
}
}

ok = true
return
}

func (p *HTTPPool) ServeHTTP(w http.ResponseWriter, r *http.Request) {
groupName, key, ok := p.parseRequest(r)
if !ok {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
groupName := parts[0]
key := parts[1]

// Fetch the value for this group/key.
group := GetGroup(groupName)
Expand Down Expand Up @@ -191,7 +221,7 @@ var bufferPool = sync.Pool{

func (h *httpGetter) Get(context Context, in *pb.GetRequest, out *pb.GetResponse) error {
u := fmt.Sprintf(
"%v%v/%v",
"%v%v/%v?escaped=true",
h.baseURL,
url.QueryEscape(in.GetGroup()),
url.QueryEscape(in.GetKey()),
Expand Down
8 changes: 5 additions & 3 deletions http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,11 @@ func TestHTTPPool(t *testing.T) {
}

func testKeys(n int) (keys []string) {
keys = make([]string, n)
for i := range keys {
keys[i] = strconv.Itoa(i)
keys = make([]string, 0)
for i := 0; i < n; i++ {
keys = append(keys, strconv.Itoa(i))
// Keys with char to be escaped
keys = append(keys, " "+strconv.Itoa(i))
}
return
}
Expand Down

0 comments on commit e652685

Please sign in to comment.