Skip to content

Instantly share code, notes, and snippets.

@noetarbouriech
Created July 24, 2023 15:39
Show Gist options
  • Save noetarbouriech/004c1c79b6b8d3fb0d093b1b2ded0005 to your computer and use it in GitHub Desktop.
Save noetarbouriech/004c1c79b6b8d3fb0d093b1b2ded0005 to your computer and use it in GitHub Desktop.
Random Cat Generator (in Go using htmx)
package main
import (
"encoding/json"
"fmt"
"html/template"
"log"
"math/rand"
"net/http"
"time"
)
type Cat struct {
ImageURL string
}
const catAPI = "https://api.thecatapi.com/v1/images/search"
func main() {
rand.Seed(time.Now().UnixNano())
http.HandleFunc("/", catHandler)
http.HandleFunc("/change", changeCatHandler)
fmt.Println("Server running on http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func catHandler(w http.ResponseWriter, r *http.Request) {
cat := Cat{ImageURL: getRandomCatImageURL()}
tmpl, err := template.New("index").Parse(`
<!DOCTYPE html>
<html>
<head>
<title>Random Cat Generator</title>
<script src="https://unpkg.com/htmx.org/dist/htmx.js"></script>
</head>
<body>
<h1>Random Cat Generator</h1>
<button id="change-button" hx-get="/change" hx-swap="innerHTML" hx-target="#cat-image">
Change Cat
</button>
<div id="cat-image">
<img src="{{.ImageURL}}" alt="Random Cat" width="300">
</div>
</body>
</html>
`)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = tmpl.Execute(w, cat)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func getRandomCatImageURL() string {
resp, err := http.Get(catAPI)
if err != nil {
log.Println("Failed to fetch cat image:", err)
return ""
}
defer resp.Body.Close()
var cats []struct {
URL string `json:"url"`
}
if err := json.NewDecoder(resp.Body).Decode(&cats); err != nil {
log.Println("Failed to decode cat image response:", err)
return ""
}
if len(cats) > 0 {
imageURL := cats[0].URL
log.Println("Fetching cat image:", imageURL)
return imageURL
}
return ""
}
func changeCatHandler(w http.ResponseWriter, r *http.Request) {
cat := Cat{ImageURL: getRandomCatImageURL()}
tmpl, err := template.New("cat").Parse(`
<img src="{{.ImageURL}}" alt="Random Cat" width="300">
`)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = tmpl.Execute(w, cat)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment