2024-08-13 16:31:28 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
|
|
|
"encoding/base64"
|
2024-10-08 22:11:06 +02:00
|
|
|
"encoding/json"
|
2024-08-13 16:31:28 +02:00
|
|
|
"html/template"
|
2024-10-08 22:11:06 +02:00
|
|
|
"net/http"
|
2024-08-13 16:31:28 +02:00
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
funcs = template.FuncMap{
|
|
|
|
"sub": func(a, b int) int {
|
|
|
|
return a - b
|
|
|
|
},
|
|
|
|
"add": func(a, b int) int {
|
|
|
|
return a + b
|
|
|
|
},
|
2024-10-08 22:11:06 +02:00
|
|
|
"translate": Translate,
|
|
|
|
"toJSON": func(v interface{}) (string, error) {
|
|
|
|
jsonBytes, err := json.Marshal(v)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return string(jsonBytes), nil
|
|
|
|
},
|
2024-08-13 16:31:28 +02:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2024-10-08 22:11:06 +02:00
|
|
|
// Helper function to render templates without elapsed time measurement
|
|
|
|
func renderTemplate(w http.ResponseWriter, tmplName string, data map[string]interface{}) {
|
|
|
|
// Parse the template with common functions (including translate)
|
|
|
|
tmpl, err := template.New(tmplName).Funcs(funcs).ParseFiles("templates/" + tmplName)
|
|
|
|
if err != nil {
|
|
|
|
printErr("Error parsing template: %v", err)
|
|
|
|
http.Error(w, Translate("internal_server_error"), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Execute the template
|
|
|
|
err = tmpl.Execute(w, data)
|
|
|
|
if err != nil {
|
|
|
|
printErr("Error executing template: %v", err)
|
|
|
|
http.Error(w, Translate("internal_server_error"), http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-13 16:31:28 +02:00
|
|
|
func generateStrongRandomString(length int) string {
|
|
|
|
bytes := make([]byte, length)
|
|
|
|
_, err := rand.Read(bytes)
|
|
|
|
if err != nil {
|
|
|
|
printErr("Error generating random string: %v", err)
|
|
|
|
}
|
|
|
|
return base64.URLEncoding.EncodeToString(bytes)[:length]
|
|
|
|
}
|
|
|
|
|
|
|
|
// Checks if the URL already includes a protocol
|
|
|
|
func hasProtocol(url string) bool {
|
|
|
|
return strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Checks if the domain is a local address
|
|
|
|
func isLocalAddress(domain string) bool {
|
|
|
|
return domain == "localhost" || strings.HasPrefix(domain, "127.") || strings.HasPrefix(domain, "192.168.") || strings.HasPrefix(domain, "10.")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ensures that HTTP or HTTPS is befor the adress if needed
|
|
|
|
func addProtocol(domain string) string {
|
|
|
|
if hasProtocol(domain) {
|
|
|
|
return domain
|
|
|
|
}
|
|
|
|
if isLocalAddress(domain) {
|
|
|
|
return "http://" + domain
|
|
|
|
}
|
|
|
|
return "https://" + domain
|
|
|
|
}
|