Home > OS >  how to parse urls correctly
how to parse urls correctly

Time:09-05

When I want to parse my url I get the following error:

panic: parse "http://x:SmT2fH": invalid port ":SmT2fH" after host

This is how I parse it:

s := "http://x:S@mT2fH#%PVfTA5gjCtn@host:5432/default"

u, err := url.Parse(s)
if err != nil {
    panic(err)
}

fmt.Println(u)

I expect x to be user and S@mT2fH#%PVfTA5gjCtn to be password.
But the errors say that it's an invalid port. because it's not port.

Does anyone know the problem?

CodePudding user response:

You need to escape the literal # as it is "reserved" by URL for indicating the start of the fragment component.

The escape code is #.

func main() {
    u, err := url.Parse("http://x:S@mT2fH#%PVfTA5gjCtn@host:5432/default")
    if err != nil {
        panic(err)
    }

    fmt.Println(u)
    fmt.Printf("%#v\n", u.User)
}

https://go.dev/play/p/xMHX-gvqhqj

  • Related