首页 > 解决方案 > : 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 。

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

谢谢并恭祝安康。临时工

标签: go

解决方案


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

如何检测:

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

fmt.Printf("%q", Location) 

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

怎么修:

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

Location = strings.TrimSpace(Location)

推荐阅读