登录
首页 >  Golang >  Go问答

URL中的第一个路径段不允许使用冒号

来源:stackoverflow

时间:2024-03-25 14:54:33 151浏览 收藏

在 Go 语言中,解析包含冒号的 URL 时可能会出现“first path segment in URL cannot contain colon”错误。该错误表示 URL 中的第一个路径段不能包含冒号。通常,这是因为从 XML 解析的 URL 中存在空格前缀或后缀,导致字符串无效。为了解决此问题,需要在使用 URL 之前对其进行整理,去除空格前缀和后缀。

问题内容

这是我的代码(部分):

type sitemapindex struct {
    // locations []location `xml:"sitemap"`
    locations []string `xml:"sitemap>loc"`
}

~~~ snip ~~~
func main(){
    var s sitemapindex
    resp, _ := http.get("https://www.washingtonpost.com/news-sitemaps/index.xml")
    bytes, _ := ioutil.readall(resp.body)
    xml.unmarshal(bytes, &s)
    for _, location := range s.locations {
        fmt.printf("%s\n", location)
        resp, err := http.get(location)
        if err != nil {
            log.fatal(err)
        } else {
            bytes, _ := ioutil.readall(resp.body)
            xml.unmarshal(bytes, &n)
            for idx := range n.titles {
                newsmap[n.titles[idx]] = newsmap{n.keywords[idx], n.locations[idx]}
            }
        }
        for idx, data := range newsmap {
            fmt.println("\n\n\n", idx)
            fmt.println("\n", data.keyword)
            fmt.println("\n", data.location)
        }
    }

现在,当我运行此代码时,我得到以下输出:

https://www.washingtonpost.com/news-sitemaps/politics.xml

2019/01/28 02:37:13 parse 
https://www.washingtonpost.com/news-sitemaps/politics.xml
: first path segment in url cannot contain colon
exit status 1

我读了一些帖子并自己做了一些实验,就像我用以下代码制作了另一个文件

package main

import ("fmt"
    "net/url")

func main(){
    fmt.Println(url.Parse("https://www.washingtonpost.com/news-sitemaps/politics.xml"))
}

并且它没有抛出任何错误,所以我知道错误与 url 无关。

现在,我几个小时前才开始使用 senddex 的教程学习 go,所以现在还没有太多想法。这是视频链接

谢谢和问候。 临时性


解决方案


这里的问题是 location 有空格前缀和后缀,因此字符串不是有效的 url。不幸的是,错误消息无助于看到这一点。

如何检测:

我通常使用 %q fmt 帮助器将字符串包装到括号中:

fmt.printf("%q", location)

将打印为“\nhttps://www.washingtonpost.com/news-sitemaps/politics.xml\n”

如何修复:

在代码中使用 location 之前添加此行:

location = strings.trimspace(location)

出现此错误的另一个原因是您使用 ip 地址时未在其前面指定协议。

您将收到此错误的情况示例:

parsedurl, err := url.parse("127.0.0.1:3213")

如何解决:

parsedUrl, err := url.Parse("http://127.0.0.1:3213")

不幸的是,文档很差。

好了,本文到此结束,带大家了解了《URL中的第一个路径段不允许使用冒号》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>