我剛開始學習 Go 中的 REST API,我不知道如何在我的 HTML 文件中顯示 GET 請求的響應。我基本上所做的是創建一個GetCurrency()從第三方 API 獲取數據的函數。現在我正在嘗試Currency在 HTML 文件中呈現響應,但我似乎沒有得到正確的結果,因為每當加載本地主機時,/getcurrency我都會得到一個空白頁面,盡管我的.gohtml文件包含一個表單。這是我在 main.go 文件中的結構type pageData struct { Title string Currency string}這是我在 main.go 文件中的主要功能func main() { http.HandleFunc("/", home) http.HandleFunc("/home", home) http.HandleFunc("/getcurrency", getCurrency) http.ListenAndServe(":5050", nil)}這是我home執行 HTML 的函數func home(w http.ResponseWriter, req *http.Request) { pd := pageData{ Title: "Etmazec Home Page", } err := tpl.ExecuteTemplate(w, "homepage.gohtml", pd) if err != nil { log.Println(err) http.Error(w, "Internal server error", http.StatusInternalServerError) }}這是我在文件getCurrency()中的功能main.gofunc getCurrency(w http.ResponseWriter, req *http.Request) { pd := pageData{ Title: "Welcome to the exchange rate website", } err := tpl.ExecuteTemplate(w, "currency.gohtml", pd) response, err := http.Get("https://api.coinbase.com/v2/prices/spot?currency=USD") if err != nil { fmt.Printf("The http requst failed with error %s \n", err) } else { data, _ := ioutil.ReadAll(response.Body) pd.Currency = string(data) fmt.Println(string(data)) }}最后,這是我的currency.gohtml身體<body> <h1>TOP HITS</h1> <nav> <ul> <li><a href="/home">HOME PAGE</a> </ul> </nav> <form action="/getcurrency" method="GET"> <label for="fname">Your Name</label> <input type="text" name="fname"> <input type="submit"> </form> {{.Currency}} </body>這是我的home.gohtml文件 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <link rel="stylesheet" href="/public/css/main.css"> <body> </body> </html>
1 回答

蠱毒傳說
TA貢獻1895條經驗 獲得超3個贊
fmt.Println(string(data))
from func getCurrency() 打印到標準輸出。因此,您會在應用程序控制臺中看到生成的 HTML,但它不會返回到瀏覽器。
https://golang.org/pkg/fmt/#Println:
Println 格式使用其操作數的默認格式并寫入標準輸出。
您需要將字節發送到w http.ResponseWriter
處理程序參數中:
fmt.Fprintln(w, string(data))
https://golang.org/pkg/fmt/#Fprintln
- 1 回答
- 0 關注
- 272 瀏覽
添加回答
舉報
0/150
提交
取消