Webchance/main.go
Gian Breitenstein 966a0bbf4a
All checks were successful
Release / publish (push) Successful in 1m0s
Deleted local winner log, winner list length capped to 20
2024-09-26 19:07:12 +02:00

72 lines
1.3 KiB
Go

package main
import (
"fmt"
"math/rand"
"net/http"
"strconv"
)
var winners []string = make([]string, 0, 20)
func main() {
http.HandleFunc("/winners", listWiners)
http.HandleFunc("/random", randomNumber)
http.Handle("/", http.FileServer(http.Dir("./static")))
http.ListenAndServe(":8080", nil)
}
func randomNumber(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
if len(name) > 15 {
w.WriteHeader(400)
return
}
chance, err := strconv.Atoi(r.URL.Query().Get("chance"))
if err != nil {
w.WriteHeader(400)
return
}
multiplicator, err := strconv.Atoi(r.URL.Query().Get("multiplicator"))
if err != nil {
w.WriteHeader(400)
return
}
won := randomize(chance, multiplicator)
if name != "" && won {
appendUser(name)
}
fmt.Fprint(w, won)
}
func randomize(chance int, mult int) bool {
r := rand.Intn(chance * mult)
if r == 0 {
if chance == 10 && mult == 1 {
return false
} else {
return true
}
} else {
if chance == 10 && mult == 1 {
return true
} else {
return false
}
}
}
func listWiners(w http.ResponseWriter, r *http.Request) {
out := ""
for _, winner := range winners {
out += winner + "\n"
}
fmt.Fprint(w, out)
}
func appendUser(username string) {
winners = append(winners, username)
if len(winners) > 20 {
winners = winners[1:]
}
}