Files
petname/main.go
Jason Swank c4d4dcd1bf wip
2026-05-17 22:59:54 -04:00

59 lines
1.2 KiB
Go

package main
import (
"fmt"
"log"
"math/rand"
"net/http"
"os"
"strconv"
"time"
"github.com/dustinkirkland/golang-petname"
)
func main() {
// Seed the random number generator
rand.Seed(time.Now().UnixNano())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Printf("Received request from %s, Host: %s", r.RemoteAddr, r.Host)
// error handling for common probes
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
// Default to 2 words, can be overridden by query param "words"
words := 2
if wParam := r.URL.Query().Get("words"); wParam != "" {
if parsed, err := strconv.Atoi(wParam); err == nil && parsed > 0 {
words = parsed
}
}
// Default separator is hyphen, can be overridden by query param "separator"
separator := "-"
if sParam := r.URL.Query().Get("separator"); sParam != "" {
separator = sParam
}
// Generate petname
name := petname.Generate(words, separator)
w.Header().Set("Content-Type", "text/plain")
fmt.Fprint(w, name)
})
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Printf("Listening on port %s", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatal(err)
}
}