Skip to content

proposal: net/url: add AppendQuery #63777

@btoews

Description

@btoews

It's pretty easy to accidentally mutate a shared URL struct when trying to create a URL with query parameters:

var redirectURL, _ = url.Parse("https://example.com")

func main() {
	http.ListenAndServe("", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		u := redirectURL
		q := u.Query()

		// opaque process that might fail
		token, err := getRedirectToken()
		if err != nil {
			q.Set("error", err.Error())
		} else {
			q.Set("token", token)
		}

		u.RawQuery = q.Encode()

		http.Redirect(w, r, u.String(), http.StatusFound)
	}))
}

APIs to help with constructing query strings and adding them to a URL — a la (*URL) JoinPath(elems ...string) *URL — could prevent this:

func (u *URL) AppendQuery(values Values) *URL {
	q := u.Query()	
	for k, v := range values {
		q[k] = append(q[k], v...)
	}

	ret := *u
	ret.RawQuery = q.Encode()

	return &ret
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions