无法在Golang中使用大猩猩Mux从网址读取变量

I am trying to write a unit test using gotests and gomock to my restful service written in golang using gorilla but service fails to get variables from the url

Here is my request

req, err := http.NewRequest("GET", "product/5b5758f9931653c36bcaf0a0", nil)

actual endpoint is product/{id}

when I step into my service at the below code

params := mux.Vars(req)

params map is empty when it should have id key mapped to 5b5758f9931653c36bcaf0a0

Strange part is endpoint works fine from post man.

May I know whats wrong with the request?

This solved the issue

req = mux.SetURLVars(req, map[string]string{"id": "5b5758f9931653c36bcaf0a0"})

Since you're using GET requests, you can use the http.Get function, it works as expected:

package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/mux"
)

func handle(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    fmt.Println(params)
}

func main() {
    m := mux.NewRouter()
    m.HandleFunc("/products/{id}", handle)
    http.Handle("/", m)
    go func() {
        http.ListenAndServe(":8080", nil)
    }()
    _, err := http.Get("http://localhost:8080/products/765")
    // Handle Error
}

If you really want to use http.NewRequest, that function doesn't actually execute the request so here is what you would need:

req, err := http.NewRequest("GET", "product/5b5758f9931653c36bcaf0a0", nil)
client := &http.Client{}
client.Do(req)