duanliang9288 2015-06-05 09:04 采纳率: 100%
浏览 499
已采纳

Golang:将URL作为GET参数传递

I want to get an URL as a get aparameter

ex: example.com?domain=site.come?a=val&b=val

the problem when i use

query := r.URL.Query()
domain := query.Get("domain") 

to get the domain name it give just domain=site.come?a=val

I think because when the r.URL.Query() meet & it consider it as a new parameter

does anyone know how can I solve this problem

Thank you in advance.

  • 写回答

1条回答 默认 最新

  • dongtanliefang8765 2015-06-05 09:13
    关注

    You need to URL-Encode your query string, like this:

    package main
    
    import (
        "fmt"
        "net/url"
    )
    
    func main() {
        query := make(url.Values)
        query.Add("domain", "example.com?foo=bar")
    
        fmt.Println(query.Encode())
    }
    

    Which outputs domain=example.com%3Ffoo%3Dbar.

    You can set that string as a RawQuery of an url.URL value and if you then access the query like you did, it will have the correct value.

    If the URL is correctly encoded then you should be able to run the following code with your URL value and get the correct result:

    package main
    
    import (
        "fmt"
        "net/url"
    )
    
    func main() {
        query := make(url.Values)
        query.Add("domain", "example.com?foo=bar&abc=123&jkl=qwe")
    
        url := &url.URL{RawQuery: query.Encode(), Host: "domain.com", Scheme: "http"}
        fmt.Println(url.String())
    
        abc := url.Query().Get("domain")
        fmt.Println(abc)
    }
    

    This prints:

    http://domain.com?domain=example.com%3Ffoo%3Dbar%26abc%3D123%26jkl%3Dqwe
    

    (the complete URI with the encoded parameter called "domain")

    example.com?foo=bar&abc=123&jkl=qwe
    

    (the decoded value of said parameter)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵
  • ¥15 cfx离心泵非稳态计算