'Non-integer slice index' when using a gorilla/mux url variable to access a slice

polaris · · 1994 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I can&#39;t seem to figure out what I&#39;m doing wrong. I have a slice of Status objects. I&#39;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&#39;s the snippet:</p> <pre><code>package main import ( &#34;encoding/json&#34; &#34;fmt&#34; &#34;github.com/gorilla/mux&#34; &#34;go_web/data&#34; &#34;net/http&#34; ) func main() { r := mux.NewRouter().StrictSlash(true) r.HandleFunc(&#34;/v1/status/&#34;, list) r.HandleFunc(&#34;/v1/status/{id}&#34;, show) http.ListenAndServe(&#34;:8000&#34;, 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[&#34;id&#34;] json.NewEncoder(w).Encode(statuses[id]) // &lt;- This throws an error } </code></pre> <hr/>**评论:**<br/><br/>StabbyCutyou: <pre><p>Wouldn&#39;t &#34;id&#34; be a string at this point? Don&#39;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>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1994 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传