Я только начал изучать REST API в Go и не могу понять, как отобразить ответ на запрос GET в моем HTML-файле.В основном я создал функцию 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.go
файле
func 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 lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<link rel="stylesheet" href="/public/css/main.css">
<body>
</body>
</html>
<h1>Currency HomePage</h1>
<nav>
<ul>
<li><a href="/home">HOME PAGE</a>
<li><a href="/getcurrency">The Currency</a>
</ul>
</nav>