pepebot/pepeservice/main.go

85 lines
1.8 KiB
Go
Raw Normal View History

2021-09-08 22:19:05 +02:00
package main
import (
"log"
"math/rand"
"net/http"
"os"
"time"
)
type application struct {
errorLog *log.Logger
infoLog *log.Logger
2021-09-23 13:24:36 +02:00
pepe_list []string
2021-09-08 22:19:05 +02:00
pepe_dir string
}
func main() {
pepe_dir := os.Getenv("PEPE_DIR")
infoLog := log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime)
errorLog := log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)
2021-09-23 13:24:36 +02:00
file, err := os.Open(pepe_dir)
if err != nil {
errorLog.Printf("Error opening pepe directory\n")
return
}
pepe_list, err := file.Readdirnames(0)
if err != nil {
errorLog.Printf("Error reading pepe directory file names\n")
return
}
file.Close()
2021-09-08 22:19:05 +02:00
app := &application{
2021-09-23 13:24:36 +02:00
infoLog: infoLog,
errorLog: errorLog,
pepe_dir: pepe_dir,
pepe_list: pepe_list,
2021-09-08 22:19:05 +02:00
}
mux := http.NewServeMux()
mux.HandleFunc("/pepe", app.sendPepe)
2021-09-23 13:30:30 +02:00
mux.HandleFunc("/reload", app.reloadList)
2021-09-08 22:19:05 +02:00
app.infoLog.Printf("Starting server at :4000\n")
2021-09-23 13:24:36 +02:00
err = http.ListenAndServe(":4000", mux)
2021-09-08 22:19:05 +02:00
log.Fatal(err)
}
func (app *application) sendPepe(w http.ResponseWriter, r *http.Request) {
// Random number generator
s := rand.NewSource(time.Now().UnixMicro())
rd := rand.New(s) // Init pseudorandom generator
2021-09-23 13:24:36 +02:00
number := rd.Intn(len(app.pepe_list))
2021-09-08 22:19:05 +02:00
baseURL := "https://cdn.nicecock.eu/pepe/1.00/"
2021-09-23 13:24:36 +02:00
URL := baseURL + app.pepe_list[number]
2021-09-08 22:19:05 +02:00
w.Write([]byte(URL))
}
2021-09-23 13:30:30 +02:00
func (app *application) reloadList(w http.ResponseWriter, r *http.Request) {
file, err := os.Open(app.pepe_dir)
if err != nil {
app.errorLog.Printf("Error opening pepe directory\n")
return
}
defer file.Close()
pepe_list, err := file.Readdirnames(0)
if err != nil {
app.errorLog.Printf("Error reading pepe directory file names\n")
return
}
app.pepe_list = pepe_list
w.WriteHeader(http.StatusOK)
w.Write([]byte("200 - Reloaded the list of pepes"))
}