:URL中的第一个路径段不能包含冒号

问题描述 投票:1回答:1

这是我的代码(部分代码):

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,几个小时前,所以现在没有太多想法。这是video link

感谢致敬。 Temporarya

go
1个回答
3
投票

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

如何检测:

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

fmt.Printf("%q", Location) 

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

怎么修:

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

Location = strings.TrimSpace(Location)
© www.soinside.com 2019 - 2024. All rights reserved.