doubi1713 2014-07-21 15:09
浏览 7

前往:与地图相关的错误

I'm rather new to Stackoverflow. I'm stuck at this problem. I'm trying to make a map.

package main

import (
    "encoding/json"
    "fmt"
    "html/template"
    "io/ioutil"
    "log"
    "net/http"
    "net/url"
    "os"
)

func main() {
    http.HandleFunc("/", handler)
    http.HandleFunc("/showimage", showimage)
    fmt.Println("listening...")
    err := http.ListenAndServe(GetPort(), nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

func GetPort() string {
    var port = os.Getenv("PORT")
    if port == "" {
        port = "4747"
        fmt.Println("INFO: No PORT environment variable detected, defaulting to " + port)
    }
    return ":" + port
}

func handler (w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, rootForm)
}

const rootForm = 
    `<!DOCTYPE html>
    <html>
        <head>
        <meta charset="utf-8">
            <title>Flickr photos</title>
        </head>
        <body>
            <h1>Flickr photos</h1>
            <p>Find photos by tags!</p>
            <form action="/showimage" method="post" accept-charset="utf-8">
                <input type="text" name="str" value="Type Tags..." id="str">
                <input type="submit" value=".. and see the images!">
            </form>
        </body>
    </html>`

var upperTemplate = template.Must(template.New("showimage").Parse(upperTemplateHTML)) //irrelevant to issue here

func showimage(w http.ResponseWriter, r *http.Request) {
    tag := r.FormValue("str")
    safeTag := url.QueryEscape(tag)
    fullUrl := fmt.Sprintf("https://api.instagram.com/v1/users/search?q=%s&access_token=ACCESS-TOKEN&count=1", safeTag)

    client := &http.Client{}

    req, err := http.NewRequest("GET", fullUrl, nil)
    if err != nil {
        log.Fatal("NewRequest: ", err)
        return
    }

    resp, requestErr := client.Do(req)
    if requestErr != nil {
        log.Fatal("Do: ", requestErr)
        return
    }

    defer resp.Body.Close()

    body, dataReadErr := ioutil.ReadAll(resp.Body)
    if dataReadErr != nil {
        log.Fatal("ReadAll: ", dataReadErr)
        return
    }


res := make(map[string][]map[string]interface{})

However, when I try to put data into the interface

json.Unmarshal(body, &res)

userid, _ := res["data"][0]["username"] 

queryUrl := fmt.Sprintf("http://instagram.com/%s", userid)

I get the error

http: panic serving [::1]:63089: runtime error: index out of range
goroutine 28 [running]:

any idea why? This error is resolved if I remove the [] in res:= and userid :=, but I won't be able to access the data I want.

  • 写回答

1条回答 默认 最新

  • doutan5798 2014-08-05 06:14
    关注

    It is wrong with "res"'s using. "res" is a map(key is string, value is a slice),so res["data"] may be a nil in your code, and it will panic when you use res["data"][0] .You should do like this:

    json.Unmarshal(body, &res)
    s, ok := res["data"]   
    if ok {
       if len(s)>0{
           userid , ok := s[0]["username"]
           if ok{
              queryUrl := fmt.Sprintf("http://instagram.com/%s", userid)
           }
       }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)