<p>I've got a handler that has a GET url of "/purchaseItems/{bidderID}/{eventID}"</p>
<p>I can't get a test to call the handler and pass in the parameters. It fails trying to parse the parameters to a number, saying it can't parse "" to an int.</p>
<p>The test:</p>
<pre><code>func TestPurchaseItems(t *testing.T) {
db := testdatabase.TestDB{}
handler := PurchaseItems(db)
server := httptest.NewServer(handler)
defer server.Close()
url := server.URL + "/purchaseItems/17/156"
resp, err := http.Get(url)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != 200 {
t.Fatalf("Received non-200 response: %d\n", resp.StatusCode)
}
expected := fmt.Sprintf("Visitor count: %d.", 1)
actual, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if expected != string(actual) {
t.Errorf("Expected the message '%s' but got '%s'\n", expected, string(actual))
}
}
</code></pre>
<p>The test error:</p>
<pre><code>http://127.0.0.1:57965/purchaseItems/17/156
ERRO[0000] strconv.ParseInt: parsing "": invalid syntax
--- FAIL: TestPurchaseItems (0.00s)
purchaseItems_test.go:38: Expected the message 'Visitor count: 1.' but got '{
"status": "ERROR",
"message": "We had some issue looking at the URL.",
"payload": null
}'
FAIL
exit status 1
FAIL mobilebid/controllers 0.012s
</code></pre>
<p>This means it isn't even parsing the parameters. Here's the handler registration code:</p>
<pre><code> r.HandleFunc("/purchaseItems/{bidderID}/{eventID}", PurchaseItems(DB)).Methods("GET")
</code></pre>
<p>I don't think I need to use the params["bidderID"] = []strings{} at all - it gives a different URL. </p>
<p>How do I at least call this handler correctly to test it?</p>
<hr/>**评论:**<br/><br/>pschlump: <pre><p>If you are using the Go library HandlerFunc it lacks the ability to process parameters in the URL. You might take a look at: <a href="http://www.gorillatoolkit.org/pkg/mux" rel="nofollow">http://www.gorillatoolkit.org/pkg/mux</a> -- It is the most popular mux -but slow - if you have a lot of URL paths. There are a bunch of them available. </p>
<p>Also please provide the server side code so that a more meaningful answer can be provided.</p></pre>natdm: <pre><p>Here's my main go file:</p>
<pre><code>package main
import (
"mobilebid/routes"
"net/http"
_ "net/http/pprof"
"time"
"github.com/joho/godotenv"
log "github.com/Sirupsen/logrus"
"github.com/gorilla/mux"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
r := mux.NewRouter()
r = routes.SetAuthenticatedRoutes(r)
r = routes.SetUnauthenticatedRoutes(r)
http.Handle("/", r)
log.WithFields(log.Fields{
"_timestamp": time.Now(),
"port": "3000",
}).Info("Starting server")
log.Fatal(http.ListenAndServe(":3000", nil))
}
</code></pre>
<p>And the routes being resolved:</p>
<pre><code>// SetUnauthenticatedRoutes sets all authenticated routes
func SetUnauthenticatedRoutes(r *mux.Router) *mux.Router {
r.HandleFunc("/purchaseItems/{bidderID}/{eventID}", PurchaseItems(DB)).Methods("GET")
return r
}
</code></pre>
<p>And the controller code for purchaseItems code (just the start, it's huge):</p>
<pre><code>func PurchaseItems(dB db.AppDB) http.HandlerFunc {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
ps := mux.Vars(req)
eventID, err := strconv.Atoi(ps["eventID"])
bidderID, err := strconv.Atoi(ps["bidderID"])
if err != nil {
log.Error(err.Error())
res.Write(ResErr(errParsingURL.Error()))
return
}
/*... rest of code... */
})
}
</code></pre></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传