package main
import (
"crypto/rand"
"encoding/json"
"fmt"
"net/http"
"strconv"
)
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const numbers = "0123456789"
const symbols = "!@#$%^&*()_+-="
func generatePassword(length int, useNumbers bool, useSymbols bool) (string, error) {
charset := letters
if useNumbers {
charset += numbers
}
if useSymbols {
charset += symbols
}
bytes := make([]byte, length)
_, err := rand.Read(bytes)
if err != nil {
return "", err
}
for i := range bytes {
bytes[i] = charset[int(bytes[i])%len(charset)]
}
return string(bytes), nil
}
func passwordHandler(w http.ResponseWriter, r *http.Request) {
length, _ := strconv.Atoi(r.URL.Query().Get("length"))
if length <= 0 {
length = 12
}
useNumbers := r.URL.Query().Get("numbers") == "true"
useSymbols := r.URL.Query().Get("symbols") == "true"
password, err := generatePassword(length, useNumbers, useSymbols)
if err != nil {
http.Error(w, "Failed to generate password", 500)
return
}
response := map[string]string{
"password": password,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func main() {
http.HandleFunc("/api/password/generate", passwordHandler)
fmt.Println("Server running on :8080")
http.ListenAndServe(":8080", nil)
}
How to use
- Run :
go run main.go Server running on :8080- Access:
http://localhost:8080/api/password/generatehttp://localhost:8080/api/password/generate?length=20&numbers=true&symbols=true
K3s Architecture
I deployed this project using K3s on Ubuntu22.
k3s is a lightweight Kubernetes distribution for running production-ready clusters on resource-limited servers.

Top comments (0)