mirror of
https://github.com/idanoo/GoCatFacts
synced 2025-07-01 06:42:14 +00:00
Compare commits
3 commits
c51b6236f0
...
748270c22a
Author | SHA1 | Date | |
---|---|---|---|
748270c22a | |||
536ac1ec68 | |||
d39591b3c0 |
4 changed files with 1325 additions and 4 deletions
|
@ -1,7 +1,10 @@
|
|||
# GoCatFacts
|
||||
|
||||
Beautiful program. HTTP server. You hit? You get fact. Boom. Default port 80.
|
||||
Quick and dirty proof of concept.
|
||||
|
||||
```shell
|
||||
go run main.go
|
||||
```
|
||||
|
||||
Initial fact list copied from https://github.com/0x27/catfacts/blob/master/catfacts.txt
|
||||
|
|
17
gocatfacts.service
Normal file
17
gocatfacts.service
Normal file
|
@ -0,0 +1,17 @@
|
|||
[Unit]
|
||||
Description=GoCatFacts
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=/root/GoCatFacts
|
||||
ExecStart=/usr/local/go/bin/go run main.go
|
||||
Environment="GOCACHE=/tmp/gocatfacts"
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
|
||||
StandardOutput=syslog
|
||||
StandardError=syslog
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
50
main.go
50
main.go
|
@ -1,9 +1,17 @@
|
|||
package gocatfacts
|
||||
package main
|
||||
|
||||
import "os"
|
||||
import (
|
||||
"bufio"
|
||||
"io"
|
||||
"log"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
var (
|
||||
port = "8080"
|
||||
facts = []string{}
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
@ -13,4 +21,42 @@ func main() {
|
|||
port = portOverride
|
||||
}
|
||||
|
||||
// Load it up
|
||||
err := loadFacts()
|
||||
if err != nil {
|
||||
log.Fatalf("Error loading facts: %v", err)
|
||||
}
|
||||
|
||||
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
io.WriteString(w, getRandomFact()+"\n")
|
||||
})
|
||||
err = http.ListenAndServe(":"+port, nil)
|
||||
if err != nil {
|
||||
log.Fatalf("Error loading facts: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// loadFacts loads cat facts from a file named "facts.txt"
|
||||
func loadFacts() error {
|
||||
file, err := os.Open("facts.txt")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
for scanner.Scan() {
|
||||
facts = append(facts, scanner.Text())
|
||||
}
|
||||
|
||||
return scanner.Err()
|
||||
}
|
||||
|
||||
// getRandomFact returns a random cat fact from the loaded facts
|
||||
func getRandomFact() string {
|
||||
if len(facts) == 0 {
|
||||
return "No facts available."
|
||||
}
|
||||
|
||||
return facts[rand.Intn(len(facts))]
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue