Skip to content

Commit 9432e3a

Browse files
committed
add GetQueryParam and GetURLParam functions
These functions retrieve the parameters and try to unescape the values.
1 parent 0253d9f commit 9432e3a

2 files changed

Lines changed: 66 additions & 0 deletions

File tree

rest/query_param.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Copyright 2023 Redpanda Data, Inc.
2+
//
3+
// Use of this software is governed by the Business Source License
4+
// included in the file licenses/BSL.md
5+
//
6+
// As of the Change Date specified in that file, in accordance with
7+
// the Business Source License, use of this software will be governed
8+
// by the Apache License, Version 2.0
9+
10+
package rest
11+
12+
import (
13+
"net/http"
14+
"net/url"
15+
)
16+
17+
// GetQueryParam retrieves the query parameter with your given key from the request,
18+
// unescapes the value and returns it. If the query parameter does not exist an
19+
// empty string will be returned. If the unescaping fails the unescaped string
20+
// will be returned.
21+
func GetQueryParam(r *http.Request, key string) string {
22+
val := r.URL.Query().Get(key)
23+
if val == "" {
24+
return ""
25+
}
26+
27+
unescapedVal, err := url.QueryUnescape(val)
28+
if err != nil {
29+
return val
30+
}
31+
return unescapedVal
32+
}

rest/url_param.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Copyright 2023 Redpanda Data, Inc.
2+
//
3+
// Use of this software is governed by the Business Source License
4+
// included in the file licenses/BSL.md
5+
//
6+
// As of the Change Date specified in that file, in accordance with
7+
// the Business Source License, use of this software will be governed
8+
// by the Apache License, Version 2.0
9+
10+
package rest
11+
12+
import (
13+
"net/http"
14+
"net/url"
15+
16+
"github.com/go-chi/chi/v5"
17+
)
18+
19+
// GetURLParam retrieves the url parameter with your given key from the request,
20+
// unescapes the value and returns it. If the url parameter does not exist an
21+
// empty string will be returned. If the unescaping fails the unescaped string
22+
// will be returned.
23+
func GetURLParam(r *http.Request, key string) string {
24+
val := chi.URLParam(r, key)
25+
if val == "" {
26+
return ""
27+
}
28+
29+
unescapedVal, err := url.PathUnescape(val)
30+
if err != nil {
31+
return val
32+
}
33+
return unescapedVal
34+
}

0 commit comments

Comments
 (0)