'Gorilla Mux Regex for number between range and predefined options
My route looks like this
max := viper.GetInt("channels")
lights_router.Path("/{channel}/{action}").
Methods("OPTIONS","GET").
Handler( util.Adapt(SerialHandler(router), util.EnableCORS()))
Channels have to be between 1 and max and action has to be either false or true.
Solution 1:[1]
func ValidetaChannel() Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
channel, err := strconv.Atoi(mux.Vars(r)["channel"])
if err != nil {
http.Error(w, http.StatusText(400), 400)
return
}
if channel >= 1 && channel <= viper.GetInt("channels") {
h.ServeHTTP(w, r)
return
}
http.Error(w, http.StatusText(400), 400)
})
}
}
func ValidetaAction() Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if mux.Vars(r)["action"] == "true" || mux.Vars(r)["action"] == "false" {
h.ServeHTTP(w, r)
return
}
http.Error(w, http.StatusText(400), 400)
})
}
}
Solution 2:[2]
filter by Route
"/{channel:(?:[0-9]{1,3})}/{action:(?:true|false)}/"
Example
package main
import (
"github.com/gorilla/mux"
"log"
"net/http"
"regexp"
"strconv"
)
var myRegex *regexp.Regexp
func main() {
mux := mux.NewRouter()
myRegex = regexp.MustCompile(`/(?P<channel>[0-9]{1,3})/(?P<action>(true|false))/`)
maxChannel := 100
mux.Path("/{channel:(?:[0-9]{1,3})}/{action:(?:true|false)}/").
HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
matchs := myRegex.FindStringSubmatch(r.URL.Path) // [all, channel, action]
/* https://stackoverflow.com/a/20751656/9935654
dict := make(map[string]string)
for i, name := range myRegex.SubexpNames() {
if i != 0 && name != "" {
dict[name] = matchs[i]
}
}
channelStr := dict["channel"]
*/
channelStr := matchs[1]
curChannel, _ := strconv.Atoi(channelStr)
if channelStr[:1] == "0" || curChannel > maxChannel {
log.Println("error")
return
}
log.Println("ok")
})
server := http.Server{Addr:":1234", Handler: mux}
server.ListenAndServe()
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CESCO |
| Solution 2 | Carson |
