package main
import (
"encoding/json"
"html/template"
"log"
"net/http"
)
type CatAPIResponse []struct {
URL string `json:"url"`
}
var tpl = template.Must(template.New("index").Parse(`
Random Cat Meme
Random Cat Meme
`))
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
tpl.Execute(w, nil)
})
http.HandleFunc("/cat", func(w http.ResponseWriter, r *http.Request) {
resp, err := http.Get("https://api.thecatapi.com/v1/images/search")
if err != nil {
http.Error(w, "Failed to fetch cat image", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
var catResp CatAPIResponse
if err := json.NewDecoder(resp.Body).Decode(&catResp); err != nil {
http.Error(w, "Failed to decode API response", http.StatusInternalServerError)
return
}
if len(catResp) == 0 {
http.Error(w, "No cat image found", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"url": catResp[0].URL})
})
log.Println("Starting server on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}