In golang How to split a URL and encode back to URL from decoded components. Any packages that do the job?
net/url helps only in decoding the URL. I want to modify the HOST
and PORT
and recreate the URL. My problem originates from the case where I receive IPV6:port
without square brackets. Let us say I get IPV6:port
in the format as:
aaa:abbb:cccc:dddd:0000:0000:00aa:bbbb:8080/static/silly.html
I want to reconstruct the URL with brackets arround IPV6 address.
I think that would not be possible. For instance, if you get:
2001:db8::1:80
How could you tell if the IP address is
2001:db8::1
Or:
2001:db8::1:80
That is the reason why RFC 5952 recommands to use brackets (or some other characters) to distinguish the IP address from the port number.
Consequently, if possible, I recommand you to ignore this ambiguous formatting.
UPDATE
Actually, you can do what you want if you are sure to be able to distinguish the two parts, which is when you can count exatcly 8 occurences of the character :
.
if strings.Count(url, ":") == 8 {
split := strings.Split(url, ":")
url = "[" + strings.Join(split[:8], ":") + "]:" + split[8]
}
But this is probably not the best idea to process this kind of url formatting anyway...
You can use the standard net
package to help in the process [Playground][http://play.golang.org/p/wz0g7rgdU4]
I use the net.ParseIP
and net.JoinHostPort
package main
import (
"fmt"
"net"
"strings"
)
func splitLastColumn(host string) (string, string, string) {
idx := strings.Index(host, "/")
col_idx := strings.LastIndex(host[:idx], ":")
return host[:col_idx], host[col_idx+1 : idx], host[idx:]
}
func main() {
ipstr := "aaa:abbb:cccc:dddd:0000:0000:00aa:bbbb:8080/static/silly.html"
host, port, path := splitLastColumn(ipstr)
ip := net.ParseIP(host)
if ip == nil {
fmt.Println("invalid addr ")
}
fmt.Println(ip, host, port, path)
fmt.Println(net.JoinHostPort(host, port))
}