-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
64 lines (51 loc) · 1.56 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main
import (
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"time"
)
var tpl *template.Template
// DogAPIResponse represents the JSON response from the dog.ceo API
type DogAPIResponse struct {
Message string `json:"message"`
Status string `json:"status"`
}
func init() {
tpl = template.Must(template.ParseFiles("templates/index.html"))
}
func main() {
http.HandleFunc("/", indexHandler)
http.HandleFunc("/getImage", imageHandler)
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
log.Println("Server started on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
tpl.ExecuteTemplate(w, "index.html", nil)
}
func imageHandler(w http.ResponseWriter, r *http.Request) {
//query := r.URL.Query().Get("query")
fmt.Println("Button Pressed!")
url := "https://dog.ceo/api/breeds/image/random"
client := &http.Client{Timeout: 10 * time.Second}
// Make the API request
resp, err := client.Get(url)
if err != nil {
log.Fatalf("Failed to make API request: %v", err)
}
defer resp.Body.Close()
// Check for non-200 status code
if resp.StatusCode != http.StatusOK {
log.Fatalf("Unexpected status code: %d", resp.StatusCode)
}
// Decode the JSON response into the DogAPIResponse struct
var apiResponse DogAPIResponse
if err := json.NewDecoder(resp.Body).Decode(&apiResponse); err != nil {
log.Fatalf("Failed to decode JSON response: %v", err)
}
w.Header().Set("Content-Type", "text/html")
tpl.ExecuteTemplate(w, "image", apiResponse)
}