I am using https://github.com/labstack/echo in one of the projects. I am using c.QueryParam
to parse the query parameter and its values. One of the values contains a
symbol in it and it converts them to a space character (which is correct). However, I would like to retain the
character in the value.
Ex: http://localhost:8080?param=test test
fmt.Println(c.QueryParam("param"))
Right now it outputs test test
. However, I am expecting the output as test test
. Is it possible to achieve it using c.QueryParam
?
CodePudding user response:
You can write a custom helper function like below -
func CustomQueryParam(c echo.Context, name string) string {
qParams := make(map[string]string)
for _, singleQueryParamStr := range strings.Split(c.QueryString(), "&") {
val := strings.Split(singleQueryParamStr, "=")
qParams[val[0]] = val[1]
}
return qParams[name]
}
func TestGet(c echo.Context) error {
param := CustomQueryParam(c, "param")
fmt.Println(param)
return c.JSON(http.StatusOK, map[string]interface{}{
"message": "request is successful",
})
}
Now, the output is as your expection. It prints test test
. But what actually CustomQueryParam
do?
Okay, let's explore the insight. Suppose, the api call is -
http://localhost:8080?param=test1 test2¶m2=test3
The CustomQueryParam
function will take an echo.Context
instance and the query param name as function parameters.
Then, inside for loop the whole query string i.e. in our case which is param=test1 test2¶m2=test3
is split by &
and stored into string slice made by each query param string ([]string{"param=test1 test2", "param2=test3"}
).
After that, we iterate over each query param string and again split into a string slice of two values having first value as param name and second value as param value. For example, for first query param string, the resultant output is like below -
"param=test1 test2"
=> []string{"param", "test1 test2"}
Then, the first value (param name) is assigned as map key and second value (param value) as map value.
After finishing above process for every query string, the map value by query param name (which is the parameter of this function) is returned.
One of the interesting fact about this custom function is that it returns empty string if query param is not found.
CodePudding user response:
You can get the raw query and then parse the parameter and it's value
func hello(c echo.Context) error {
//to get the raw query
fmt.Println(c.Request().URL.RawQuery)
return c.String(http.StatusOK, "Hello, World!")
}
Then you can use strings.split(rawQuery,"=")
to get the parameter and it's value.