Horizontal optional query values

I was working on a Go project that uses gorilla / mux as a router.

I need to have query values ​​associated with the route, but these values ​​should be optional. This means that I would like to catch both /articles/123, and /articles/123?key=456in the same handler.

For this, I tried to use a method r.Queriesthat accepts key / value pairs: router. Path("/articles/{id:[0-9]+}"). Queries("key", "{[0-9]*?}") but this only makes the value ( 456) optional, but not key. Thus, both parameters /articles/123?key=456and /articles/123?key=valid, but are not /articles/123.

Edit: Another requirement is that after registering the route, I would like to develop them programmatically, and I can’t figure out how to use it r.Queries, even if the documents indicate that it is possible ( https://github.com/gorilla/mux# registered-urls ).

@jmaloney responds, but does not allow the creation of URLs from names.

+4
source share
2 answers

I would just register your handler twice.

router.Path("/articles/{id:[0-9]+}").Queries("key", "{[0-
9]*?}").HandlerFunc(YourHandler).Name("YourHandler")

router.Path("/articles/{id:[0-9]+}").HandlerFunc(YourHandler)

Shown here is a work program for demonstration. Please note that I use r.FormValueto get the query parameter.

. , go get -u github.com/gorilla/mux, . URL.

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

var router = mux.NewRouter()

func main() {
    router.Path("/articles/{id:[0-9]+}").Queries("key", "{key}").HandlerFunc(YourHandler).Name("YourHandler")
    router.Path("/articles/{id:[0-9]+}").HandlerFunc(YourHandler)

    if err := http.ListenAndServe(":9000", router); err != nil {
        log.Fatal(err)
    }
}

func YourHandler(w http.ResponseWriter, r *http.Request) {
    id := mux.Vars(r)["id"]
    key := r.FormValue("key")

    u, err := router.Get("YourHandler").URL("id", id, "key", key)
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    // Output:
    // /articles/10?key=[key]
    w.Write([]byte(u.String()))
}
+5

, doc:

, , , .

, : id, found := mux.Vars(r)["id"]. found , .

0

Source: https://habr.com/ru/post/1682514/


All Articles