URL path using Gorilla Mux or Httprouter?

I am using the built- in net/http router. If the url is

https://localhost:9999/product/10

I have used

strings.Trim(r.URL.Path, "/") to get path product and
r.URL.Query().Get("id") to get the value 10

But I have found no way to get the corresponding path using Gorilla Mux. Or
julienschmidt httprouter

How do I get the path using the other routers?

route : /v1/product/{id:[0-9]+}

func Get(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
  vars := mux.Vars(r)
  id := vars["id"]
}

I have some difficulties to put this in a context. How do I use this? Gorilla?

You nave import the github.com/gorilla/mux in your controller or middleware, when you receive the r *http.Request, and use it the same away

something like that

import (
  "github.com/gorilla/mux"
)

func Get(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
  vars := mux.Vars(r)
  id := vars["id"]
}

The context I am looking for is this:

func main() {
	r := mux.NewRouter()
    path := mux.Vars(r)
    val := vars["id"]

	r.HandleFunc("/{path}/{val}",{path}).Methods(http.MethodPost)
	r.HandleFunc("/{path}/{val}",{path}).Methods(http.MethodGet)
	r.HandleFunc("/{path}/{val}",{path}).Methods(http.MethodPut)
	r.HandleFunc("/{path}/{val}",{path}).Methods(http.MethodDelete)
	r.HandleFunc("/", notFound)
	log.Fatal(http.ListenAndServe(":9999", nil))
}

I want the path to be more dynamic. I use this on my test site using net/http The Web Server and it works perfect.

My goal is to replace net/http with Gorilla Mux OR httprouter instead. Is this possible?

is the same, you put the mux.Vars into your mothods/functions

package main

import (
	"fmt"
	"github.com/gorilla/mux"
	"log"
	"net/http"
)

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

	fmt.Println(id)

	w.Write([]byte("Gorilla!\n"))
}

func main() {
	r := mux.NewRouter()
	// Routes consist of a path and a handler function.
	r.HandleFunc("/product/{id:[0-9]+}", YourHandler)

	// Bind to a port and pass our router in
	log.Fatal(http.ListenAndServe(":8000", r))
}

try this example, is the same above
https://github.com/gorilla/mux#full-example

  1. What if the path is dynamic (Url.Path)? Like /{path}/ instead of /product/?
  2. How to handle GET, PUT, DELETE and UPDATE? (REST API)

My main question is about avoiding static path. I have over 600 endpoints, Static endpoints (paths) may be hard to manage.

If it you want work with static files, there are a example on the repository to work with it, here:
https://github.com/gorilla/mux#static-files

To set the methods to your “handlers” puts this on the final, Methods("POST")
https://github.com/gorilla/mux#walking-routes

see the examples

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.