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

时间:2018-07-25 14:49:59

标签: rest unit-testing go gorilla mux

我正在尝试使用getests和gomock编写单元测试到使用大猩猩用golang编写的静态服务中,但是服务无法从url中获取变量

这是我的要求

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

实际终点为product/{id}

当我通过以下代码进入服务时

params := mux.Vars(req)

params映射为空,应将id键映射到5b5758f9931653c36bcaf0a0

奇怪的是端点对于邮递员来说效果很好。

我可以知道请求有什么问题吗?

3 个答案:

答案 0 :(得分:1)

这解决了问题

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

答案 1 :(得分:0)

由于使用的是GET请求,因此可以使用http.Get函数,该函数可以按预期工作:

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
}

如果您确实要使用http.NewRequest,则该函数实际上不会执行请求,因此这是您需要的:

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

答案 2 :(得分:0)

在源代码中的单独函数中创建多路复用器路由器,然后在测试中直接调用它。

在源代码中:

func Router() *mux.Router {
  r := mux.NewRouter()
  r.HandleFunc("/product/{id}", productHandler)

  return r
}

func main() {
http.Handle("/", Router())
}

测试中:

func TestProductHandler(t *testing.T) {
  r := http.NewRequest("GET", "product/5b5758f9931653c36bcaf0a0", nil)
  w := httptest.NewRecorder()

  Router().ServeHTTP(w, r)
}

在一个Google网上论坛中找到了相关的解决方案。 https://groups.google.com/forum/#!msg/golang-nuts/Xs-Ho1feGyg/xg5amXHsM_oJ