golang 解析html时把url转绝对路径
// 返回url的绝对地址
// currUrl 当前url
func absUrl(currUrl, baseUrl string) string {
urlInfo, err := url.Parse(currUrl)
if err != nil {
return ""
}
if urlInfo.Scheme != "" {
return currUrl
}
baseInfo, err := url.Parse(baseUrl)
if err != nil {
return ""
}
u := baseInfo.Scheme + "://" + baseInfo.Host
var path string
if strings.Index(urlInfo.Path, "/") == 0 {
path = urlInfo.Path
} else {
path = filepath.Dir(baseInfo.Path) + "/" + urlInfo.Path
}
rst := make([]string, 0)
pathArr := strings.Split(path, "/")
// 如果path是已/开头,那在rst加入一个空元素
if pathArr[0] == "" {
rst = append(rst, "")
}
for _, p := range pathArr {
if p == ".." {
if rst[len(rst)-1] == ".." {
rst = append(rst, "..")
} else {
rst = rst[:len(rst)-1]
}
} else if p != "" && p != "." {
rst = append(rst, p)
}
}
return u + strings.Join(rst, "/")
}