为什么gourl.ParseQuery方法的结果如此出乎意料?

huangapple go评论285阅读模式
英文:

Why is the result of the gourl.ParseQuery method so unexpected?

问题

这个程序的结果是{"x":["1 1 3"], "y":["2", "3"]}。但为什么不是{"x":["1+1+3"], "y":["2", "3"]}呢?要得到期望的结果"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), ",", ", ")
}

沙箱链接:https://go.dev/play/p/o0TiRTVpaQk

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

英文:

The result of this program is {"x":["1 1 3"], "y":["2", "3"]}.
But why is 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), ",", ", ")
}

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

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

答案1

得分: 0

url.ParseQuery+替换为

相关代码片段:

        case '+':
			if mode == encodeQueryComponent {
				t.WriteByte(' ')
			} else {
				t.WriteByte('+')
			}

解决方案是对+进行编码(将它们替换为%2B

如下所示:

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), ",", ", ")
}
英文:

url.ParseQuery replaces + with

relevant code fragment:

        case '+':
			if mode == encodeQueryComponent {
				t.WriteByte(' ')
			} else {
				t.WriteByte('+')
			}

the solution is to encode + (replace them with %2B)

like so:

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), ",", ", ")
}

huangapple
  • 本文由 发表于 2023年5月16日 00:01:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76255932.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定