Go:地图相关的错误

时间:2014-07-21 15:09:19

标签: go

我是Stackoverflow的新手。我坚持这个问题。我正在尝试制作地图。

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{})

但是,当我尝试将数据放入界面时

json.Unmarshal(body, &res)

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

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

我收到错误

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

任何想法为什么?如果我删除res:=和userid:=中的[],则会解决此错误,但我将无法访问所需的数据。

1 个答案:

答案 0 :(得分:0)

“res”的使用是错误的。 “res”是一个映射(键是字符串,值是一个切片),因此res [“data”]可能是代码中的nil,当你使用res [“data”]时它会发生混乱0]。你应该这样做:

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)
       }
   }
}