All checks were successful
Docker Release Build / push_to_registry (push) Successful in 1m2s
95 lines
2.5 KiB
Go
95 lines
2.5 KiB
Go
package main
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"html/template"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
const (
|
|
passwordLength = 32
|
|
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
|
)
|
|
|
|
var templates = make(map[string]*template.Template)
|
|
var AppVersion = "development"
|
|
|
|
func loadTemplates() {
|
|
// 1. FuncMap definieren
|
|
funcMap := template.FuncMap{
|
|
"getAppVersion": func() string {
|
|
return AppVersion
|
|
},
|
|
}
|
|
|
|
// 2. Templates mit FuncMap laden
|
|
// Wir nutzen New("base.html"), da base.html meist das Haupt-Layout definiert
|
|
templates["index.html"] = template.Must(template.New("base.html").Funcs(funcMap).ParseFiles(
|
|
"templates/base.html",
|
|
"templates/index.html",
|
|
))
|
|
|
|
templates["help.html"] = template.Must(template.New("base.html").Funcs(funcMap).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))
|
|
}
|