Parsing URL with matrix paramers using net/url built-in package

368 Views Asked by At

It seems that URL does not support matrix parameters

// From net/url
type URL struct {
        Scheme   string
        Opaque   string    // encoded opaque data
        User     *Userinfo // username and password information
        Host     string    // host or host:port
        Path     string
        RawQuery string // encoded query values, without '?'
        Fragment string // fragment for references, without '#'
}
  • Why ?
  • How can I extract matrix parameters from an URL ? and when should I use them instead of using requests parameters embedded in the request.URL.RawQuery part of the URL ?
1

There are 1 best solutions below

0
On

The parameters end up getting put in url.Path. Here's a function which can put them in the Query for you:

func ParseWithMatrix(u string) (*url.URL, error) {
    parsed, err := url.Parse(u)
    if err != nil {
        return nil, err
    }
    if strings.Contains(parsed.Path, ";") {
        q := parsed.Path[strings.Index(parsed.Path, ";")+1:]
        m, err := url.ParseQuery(q)
        if err != nil {
            return nil, err
        }
        for k, vs := range parsed.Query() {
            for _, v := range vs {
                m.Add(k, v)
            }
        }
        parsed.Path = parsed.Path[:strings.Index(parsed.Path, ";")]
        parsed.RawQuery = m.Encode()
    }
    return parsed, nil
}