go - : 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,几个小时前,所以现在还没有太多想法。这是视频链接
谢谢并恭祝安康。临时工
解决方案
这里的问题是Location
有空格前缀和后缀,所以字符串不是有效的 URL。不幸的是,错误消息无助于看到这一点。
如何检测:
我通常使用fmt
将字符串包装到括号中的 %q 助手:
fmt.Printf("%q", Location)
将打印为“\nhttps://www.washingtonpost.com/news-sitemaps/politics.xml\n”
怎么修:
在代码中使用 Location 之前添加此行:
Location = strings.TrimSpace(Location)
推荐阅读
- couchbase - 过滤器上的 Couchbase 二级索引
- javascript - DataTables 动态单元格不会呈现
- reactjs - 节点模块如何解析文件路径?
- android - 如果 onFocusChangeListener 被钩住,TextInputEditText 的奇怪行为
- javascript - Kendo UI - 修改时文本颜色变化
- python-3.x - Python - 无法使用套接字模块将客户端与服务器(在 Windows 2012 R2 上)连接
- nao-robot - 为什么 NAO 的启动会干扰我的默认行为?
- spring - @Autowired 如何使用反射以及如何调用适当的 Setter 方法
- php - 如何捕获异常 DB::unprepared()
- python - 将采样行添加到数据帧并计算平均值的更 Pythonic 方式