Go 从flickr api获取照片
我是新来的。我正在尝试构建一个简单的应用程序,让用户通过在表单中键入标签从flickr获取照片。我被当前代码(粘贴在下面)卡住了,因为当我单击submit按钮时,页面/showimage上没有显示任何内容。我在代码中做错了什么Go 从flickr api获取照片,go,Go,我是新来的。我正在尝试构建一个简单的应用程序,让用户通过在表单中键入标签从flickr获取照片。我被当前代码(粘贴在下面)卡住了,因为当我单击submit按钮时,页面/showimage上没有显示任何内容。我在代码中做错了什么 package main import ( "encoding/json" "fmt" "html/template" "io/ioutil" "log" "net/http" "net/url" "os"
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))
func showimage(w http.ResponseWriter, r *http.Request) {
tag := r.FormValue("str")
safeTag := url.QueryEscape(tag)
apiKey := "MYAPIKEY"
fullUrl := fmt.Sprintf("https://api.flickr.com/services/rest/?method=flickr.people.getPhotos&api_key=%s&tags=%s", apiKey, 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]map[string]interface{}, 0)
json.Unmarshal(body, &res)
owner, _ := res["photos"]["photo"]["owner"]
id, _ := res["photos"]["photo"]["id"]
queryUrl := fmt.Sprintf("http://flickr.com/photos/%s/%s", owner, id)
tempErr := upperTemplate.Execute(w, queryUrl)
if tempErr != nil {
http.Error(w, tempErr.Error(), http.StatusInternalServerError)
}
}
const upperTemplateHTML =
`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Display images</title>
</head>
<body>
<h3>Images</h3>
<img src="{{html .}}" alt="Image" />
</body>
</html>`
主程序包
进口(
“编码/json”
“fmt”
“html/模板”
“io/ioutil”
“日志”
“net/http”
“网络/网址”
“操作系统”
)
func main(){
http.HandleFunc(“/”,handler)
http.HandleFunc(“/showimage”,showimage)
fmt.Println(“倾听…”)
错误:=http.ListenAndServe(GetPort(),nil)
如果错误!=零{
log.Fatal(“ListendServe:,错误)
}
}
func GetPort()字符串{
var port=os.Getenv(“端口”)
如果端口==“”{
port=“4747”
fmt.Println(“信息:未检测到端口环境变量,默认为“+端口”)
}
返回“:”+端口
}
func处理程序(w http.ResponseWriter,r*http.Request){
格式打印(w,根形)
}
常量根形式=
`
Flickr照片
Flickr照片
通过标签查找照片
`
var upperTemplate=template.Must(template.New(“showimage”).Parse(upperTemplateHTML))
func showimage(w http.ResponseWriter,r*http.Request){
标记:=r.FormValue(“str”)
safeTag:=url.QueryEscape(标记)
apiKey:=“MYAPIKEY”
fullUrl:=fmt.Sprintf(“https://api.flickr.com/services/rest/?method=flickr.people.getPhotos&api_key=%s&tags=%s,apiKey,safeTag)
客户端:=&http.client{}
req,err:=http.NewRequest(“GET”,fullUrl,nil)
如果错误!=零{
log.Fatal(“NewRequest:,err)
回来
}
resp,requestErr:=client.Do(req)
如果请求错误!=nil{
log.Fatal(“Do:”,requestErr)
回来
}
延迟响应主体关闭()
body,dataReadErr:=ioutil.ReadAll(resp.body)
如果dataReadErr!=nil{
log.Fatal(“ReadAll:,dataReadErr”)
回来
}
res:=make(map[string]map[string]map[string]接口{},0)
json.Unmarshal(body和res)
所有者,\:=res[“照片”][“照片”][“所有者”]
id,\:=res[“photos”][“photo”][“id”]
queryUrl:=fmt.Sprintf(“http://flickr.com/photos/%s/%s“,所有者,id)
tempErr:=upperTemplate.Execute(w,queryUrl)
如果温度!=零{
http.Error(w,tempErr.Error(),http.StatusInternalServerError)
}
}
常量upperTemplateHTML=
`
显示图像
图像
`
两件事:
1) http.HandleFunc(“showimage”,showimage)应该是http.HandleFunc(“/showimage”,showimage)
2) MyAPI密钥可能不是有效的api密钥。谢谢!是的,这是一串数字。我在代码中写下了自己的api密钥。我已经修复了/showimage代码,现在它将我带到另一个页面,但图像是broken@AUL您可以检查响应正文和图像urlI,但我有以下错误:GET 400(错误请求)@AUL json.Unmarshal(body,&res)可能返回error@AULfullUrl:=fmt.Sprintf(“,apiKey,safeTag)在这里您将输入标记设置为user_id参数,对吗?