Skip to content

Commit 7b7eb1d

Browse files
committed
http: support QueryUnescape in HTTPPool.ServeHTTP
HTTPPool will inverse escaped path if query parameter contains "escaped=true". Add keys with char to be escaped in test.
1 parent 84a468c commit 7b7eb1d

File tree

2 files changed

+36
-8
lines changed

2 files changed

+36
-8
lines changed

http.go

+31-5
Original file line numberDiff line numberDiff line change
@@ -138,19 +138,45 @@ func (p *HTTPPool) PickPeer(key string) (ProtoGetter, bool) {
138138
return nil, false
139139
}
140140

141-
func (p *HTTPPool) ServeHTTP(w http.ResponseWriter, r *http.Request) {
142-
// Parse request.
141+
func (p *HTTPPool) parseRequest(r *http.Request) (string, string, bool) {
143142
if !strings.HasPrefix(r.URL.Path, p.opts.BasePath) {
144143
panic("HTTPPool serving unexpected path: " + r.URL.Path)
145144
}
146145
parts := strings.SplitN(r.URL.Path[len(p.opts.BasePath):], "/", 2)
147146
if len(parts) != 2 {
148-
http.Error(w, "bad request", http.StatusBadRequest)
149-
return
147+
return "", "", false
150148
}
151149
groupName := parts[0]
152150
key := parts[1]
153151

152+
queries, err := url.ParseQuery(r.URL.RawQuery)
153+
if err != nil {
154+
// Still accept groupName and key in path.
155+
return groupName, key, true
156+
}
157+
158+
var uerr error
159+
if queries.Get("escaped") == "true" {
160+
groupName, uerr = url.QueryUnescape(groupName)
161+
if uerr != nil {
162+
return "", "", false
163+
}
164+
key, uerr = url.QueryUnescape(key)
165+
if uerr != nil {
166+
return "", "", false
167+
}
168+
}
169+
170+
return groupName, key, true
171+
}
172+
173+
func (p *HTTPPool) ServeHTTP(w http.ResponseWriter, r *http.Request) {
174+
groupName, key, ok := p.parseRequest(r)
175+
if !ok {
176+
http.Error(w, "bad request", http.StatusBadRequest)
177+
return
178+
}
179+
154180
// Fetch the value for this group/key.
155181
group := GetGroup(groupName)
156182
if group == nil {
@@ -191,7 +217,7 @@ var bufferPool = sync.Pool{
191217

192218
func (h *httpGetter) Get(context Context, in *pb.GetRequest, out *pb.GetResponse) error {
193219
u := fmt.Sprintf(
194-
"%v%v/%v",
220+
"%v%v/%v?escaped=true",
195221
h.baseURL,
196222
url.QueryEscape(in.GetGroup()),
197223
url.QueryEscape(in.GetKey()),

http_test.go

+5-3
Original file line numberDiff line numberDiff line change
@@ -103,9 +103,11 @@ func TestHTTPPool(t *testing.T) {
103103
}
104104

105105
func testKeys(n int) (keys []string) {
106-
keys = make([]string, n)
107-
for i := range keys {
108-
keys[i] = strconv.Itoa(i)
106+
keys = make([]string, 0)
107+
for i := 0; i < n; i++ {
108+
keys = append(keys, strconv.Itoa(i))
109+
// Keys with char to be escaped
110+
keys = append(keys, " "+strconv.Itoa(i))
109111
}
110112
return
111113
}

0 commit comments

Comments
 (0)