dongmanzui8486 2015-02-16 12:12
浏览 1027

如何在Go中编码包含空格或特殊字符的URL?

I have a URL containing spaces and special characters, like the following example:

http://localhost:8182/graphs/graph/tp/gremlin?script=g.addVertex(['id':'0af69422 5be','date':'1968-01-16 00:00:00 +0000 UTC'])

How can I encode URLs like this in Go?

  • 写回答

1条回答 默认 最新

  • dswy34539 2015-02-16 12:21
    关注

    Url encoding is provided in the net/url package. You have functions such as:

    url.QueryEscape("g.addVertex(['id':'0af69422 5be','date':'1968-01-16 00:00:00 +0000 UTC'])")
    

    Which gives you:

    g.addVertex%28%5B%27id%27%3A%270af69422+5be%27%2C%27date%27%3A%271968-01-16+00%3A00%3A00+%2B0000+UTC%27%5D%29

    Also check out url.URL and url.Values. Depending on your needs, these will solve it for you.

    If you only have the entire URL you can try to parse it and then re-encode the broken query part like this:

    u, err := url.Parse("http://localhost:8182/graphs/graph/tp/gremlin?script=g.addVertex(['id':'0af69422 5be','date':'1968-01-16 00:00:00 +0000 UTC'])")
    if err != nil {
        panic(err)
    }   
    u.RawQuery = u.Query().Encode()
    fmt.Println(u)
    

    However, be careful. If the string contains and ampersands (&) or hashmarks (#), it will not give the result you are expecting.

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100