Webchance/main.go

63 lines
1.2 KiB
Go
Raw Normal View History

2024-09-26 16:43:51 +02:00
package main
import (
"fmt"
2024-09-26 17:46:12 +02:00
"log"
2024-09-26 16:43:51 +02:00
"math/rand"
"net/http"
"strconv"
)
var winners []string = make([]string, 0, 20)
func main() {
2024-09-26 17:46:12 +02:00
http.HandleFunc("/winners", listWiners)
2024-09-26 16:43:51 +02:00
http.HandleFunc("/random", randomNumber)
http.Handle("/", http.FileServer(http.Dir("./static")))
http.ListenAndServe(":8080", nil)
}
func randomNumber(w http.ResponseWriter, r *http.Request) {
2024-09-26 17:46:12 +02:00
name := r.URL.Query().Get("name")
2024-09-26 16:43:51 +02:00
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)
2024-09-26 17:46:12 +02:00
log.Println(name)
2024-09-26 18:24:40 +02:00
if name != "" && won {
2024-09-26 17:46:12 +02:00
winners = append(winners, name)
fmt.Println(winners)
}
2024-09-26 16:43:51 +02:00
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
}
}
}
2024-09-26 17:46:12 +02:00
func listWiners(w http.ResponseWriter, r *http.Request) {
2024-09-26 18:24:40 +02:00
out := ""
for _, winner := range winners {
out += winner + "\n"
}
fmt.Fprint(w, out)
2024-09-26 17:46:12 +02:00
}