curl support, no html in that case

This commit is contained in:
Weetile 2024-11-24 22:16:17 +00:00
parent 621314b7bc
commit 88ec940b9b

54
main.go
View File

@ -17,7 +17,6 @@ func loadFacts() ([]string, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
// Split the file into lines and return as a slice // Split the file into lines and return as a slice
lines := string(data) lines := string(data)
return splitLines(lines), nil return splitLines(lines), nil
@ -32,34 +31,46 @@ func randomFactHandler(facts []string) http.HandlerFunc {
// Get a random index // Get a random index
index := rand.Intn(len(facts)) index := rand.Intn(len(facts))
// Write the random fact as an HTML response with CSS // Check if the request is from curl by looking at the User-Agent
userAgent := r.Header.Get("User-Agent")
isCurl := strings.HasPrefix(strings.ToLower(userAgent), "curl")
if isCurl {
// For curl requests, just return the fact as plain text
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, facts[index])
return
}
// For browser requests, return the HTML version
w.Header().Set("Content-Type", "text/html")
fmt.Fprintf(w, ` fmt.Fprintf(w, `
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Fact</title> <title>Random Fact</title>
<style> <style>
body { body {
background-color: #24273a; background-color: #24273a;
color: #8aadf4; color: #8aadf4;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
height: 100vh; height: 100vh;
margin: 0; margin: 0;
font-size: 24px; /* Increase text size */ font-size: 24px;
font-weight: bold; font-weight: bold;
font-family: Arial, sans-serif; font-family: Arial, sans-serif;
} }
</style> </style>
</head> </head>
<body> <body>
<p>%s</p> <p>%s</p>
</body> </body>
</html> </html>
`, facts[index]) `, facts[index])
} }
} }
@ -78,3 +89,4 @@ func main() {
panic(err) panic(err)
} }
} }