Why are the results of the gourl.ParseQuery method so unexpected?

PHPz
Release: 2024-02-10 16:50:07
forward
1131 people have browsed it

为什么 gourl.ParseQuery 方法的结果如此意外?

In PHP development, the gourl.ParseQuery method is widely used to parse URL query strings. However, sometimes we find that the results of this method are unexpected and confusing. Why does this accident happen? PHP editor Baicao will explore this problem in this article and provide some solutions. Let’s take a look!

Question content

The result of this program is{"x":["1 1 3"], "y":["2", "3"]}. But why not {"x":["1 1 3"], "y":["2", "3"]}? What do I need to do to get the expected result"1 1 3"?

import (
    "encoding/json"
    "fmt"
    "log"
    "net/url"
    "strings"
)

func main() {
    m, err := url.ParseQuery(`x=1+1+3&y=2&y=3`)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(toJSON(m))
}

func toJSON(m any) string {
    js, err := json.Marshal(m)
    if err != nil {
        log.Fatal(err)
    }
    return strings.ReplaceAll(string(js), ",", ", ")
}
Copy after login

Sandbox: https://go.dev/play/p/o0tirtvpaqk

{"x":["1 1 3"], "y":["2", "3"]}

Solution

url.parsequery Replace with

Related code snippets:

case '+':
            if mode == encodequerycomponent {
                t.writebyte(' ')
            } else {
                t.writebyte('+')
            }
Copy after login

The solution is to encode (replace with +)

like this:

import (
    "encoding/json"
    "fmt"
    "log"
    "net/url"
    "strings"
)

func main() {
    m, err := url.ParseQuery(`x=1%2B1%2B3&y=2&y=3`)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(toJSON(m))
}

func toJSON(m any) string {
    js, err := json.Marshal(m)
    if err != nil {
        log.Fatal(err)
    }
    return strings.ReplaceAll(string(js), ",", ", ")
}
Copy after login

The above is the detailed content of Why are the results of the gourl.ParseQuery method so unexpected?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!