gpt4 book ai didi

Go: map 相关错误

转载 作者:数据小太阳 更新时间:2023-10-29 03:37:45 25 4
gpt4 key购买 nike

我是 Stackoverflow 的新手。我被困在这个问题上。我正在尝试制作 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{})

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

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 := 中的 [],此错误将得到解决,但我将无法访问我想要的数据。

最佳答案

“res”的用法是错误的。 "res"是一个map(key是string,value是slice),所以res["data"]在你的代码中可能是一个nil,当你使用res["data时它会panic "][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)
}
}
}

关于Go: map 相关错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24868531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com