package main
import (
"crypto/rand"
"html/template"
"log"
"net/http"
)
const (
passwordLength = 32
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
)
//var tmpl *template.Template
var templates = make(map[string]*template.Template)
func loadTemplates() {
templates["index.html"] = template.Must(template.ParseFiles("templates/base.html", "templates/index.html"))
templates["help.html"] = template.Must(template.ParseFiles("templates/base.html", "templates/help.html"))
log.Printf("Alle Templates erfolgreich geladen")
}
func generatePassword() string {
password := make([]byte, passwordLength)
_, err := rand.Read(password)
if err != nil {
log.Fatal(err)
}
for i := 0; i < passwordLength; i++ {
password[i] = chars[int(password[i])%len(chars)]
}
return string(password)
}
func passwordHandler(w http.ResponseWriter, r *http.Request) {
password := generatePassword()
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(password))
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("call indexHandler: Request %s %s\n", r.Method, r.URL)
password := generatePassword()
data := struct {
Password string
}{
Password: password,
}
err := templates["index.html"].ExecuteTemplate(w, "base.html", data)
if err != nil {
log.Printf("Fehler beim Rendern des Templates: %v", err)
http.Error(w, "Interner Serverfehler", http.StatusInternalServerError)
}
}
func helpHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("call helpHandler\n")
err := templates["help.html"].ExecuteTemplate(w, "base.html", nil)
if err != nil {
log.Printf("Fehler beim Rendern des Templates: %v", err)
http.Error(w, "Interner Serverfehler", http.StatusInternalServerError)
}
}
func main() {
loadTemplates()
fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
http.HandleFunc("/", indexHandler)
http.HandleFunc("/api/password", passwordHandler)
http.HandleFunc("/help", helpHandler)
log.Println("Server läuft auf http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}