<p>I can't seem to figure out what I'm doing wrong. I have a slice of Status objects. I'm trying to return one by using a path variable from the gorilla/mux library. Any help would be appreciated. </p>
<p>Thanks!</p>
<p>Here's the snippet:</p>
<pre><code>package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"go_web/data"
"net/http"
)
func main() {
r := mux.NewRouter().StrictSlash(true)
r.HandleFunc("/v1/status/", list)
r.HandleFunc("/v1/status/{id}", show)
http.ListenAndServe(":8000", r)
}
func list(w http.ResponseWriter, r *http.Request) {
statuses := data.MakeDummyData()
json.NewEncoder(w).Encode(statuses)
}
func show(w http.ResponseWriter, r *http.Request) {
statuses := data.MakeDummyData()
urlParameters := mux.Vars(r)
id := urlParameters["id"]
json.NewEncoder(w).Encode(statuses[id]) // <- This throws an error
}
</code></pre>
<hr/>**评论:**<br/><br/>StabbyCutyou: <pre><p>Wouldn't "id" be a string at this point? Don't you need to convert it?</p>
<pre><code>i, err := strconv.Atoi(id)
if err != nil {
//handle this
}
json.NewEncoder(w).Encode(statuses[i])
</code></pre></pre>potatofloss: <pre><p>I knew it was something stupid. Thanks so much!</p></pre>stupidworkalt: <pre><p>No magic type conversions!</p></pre>
'Non-integer slice index' when using a gorilla/mux url variable to access a slice
polaris · · 2031 次点击这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传