2025-02-19 20:39:05 +01:00

127 lines
2.5 KiB
Go

package main
import (
"bufio"
"math/rand"
"net/http"
"os"
"regexp"
"strconv"
"github.com/gin-gonic/gin"
)
// devolve un array co listado de palabros do arquivo palabras.txt
func read_words() []string {
readFile, err := os.Open("palabras.txt")
if err != nil {
panic(err)
}
defer readFile.Close()
fileScanner := bufio.NewScanner(readFile)
fileScanner.Split(bufio.ScanLines)
var fileLines []string
for fileScanner.Scan() {
fileLines = append(fileLines, fileScanner.Text())
}
return fileLines
}
// devolve unha palabra random
func random_word(list []string) string {
return list[rand.Intn(len(list))]
}
// monta a frase a usar como contrasinal
func generate_password(list []string, cantidade int, separator string) string {
phrase := ""
for i := range cantidade {
if i == cantidade-1 {
// ultimo elemento
phrase = phrase + random_word(list)
} else {
phrase = phrase + random_word(list) + separator
}
}
return phrase
}
// xenera resposta
type resposta struct {
code int
chave string
valor string
}
func generate_response(c *gin.Context, listado []string) resposta {
resp := resposta{}
num := c.Query("num")
sep := c.Query("sep")
if num == "" {
num = "4" // cantidade por defecto
}
if sep == "" {
sep = " " // separador por defecto
}
isNumber := regexp.MustCompile(`^\d*$`)
if !isNumber.MatchString(num) {
resp.code = 400
resp.chave = "error"
resp.valor = "O parámetro 'num' ten que ser un número."
} else {
// xenera unha frase de 'num' palabras
n, _ := strconv.Atoi(num) // o erro non fai falta, foi comprobado no regexp
if n >= 128 {
// limitase a sacho
n = 128
}
resp.code = 200
resp.chave = "password"
resp.valor = generate_password(listado, n, sep)
}
// resp.code sera o 200 e logo chave e valor o JSON do gin.H
// c.JSON(200, gin.H{
// "password": generate_password(listado, n, sep),
// })
return resp
}
func main() {
// lemos a memoria o arquivo de palabras
listado := read_words()
// arrancamos gin
r := gin.Default()
r.LoadHTMLGlob("templates/*")
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
// /pass?num=4&sep=-
r.GET("/pass", func(c *gin.Context) {
resp := generate_response(c, listado)
c.JSON(resp.code, gin.H{
resp.chave: resp.valor,
})
})
r.GET("/", func(c *gin.Context) {
resp := generate_response(c, listado)
c.HTML(http.StatusOK, "index.tmpl", gin.H{
resp.chave: resp.valor,
})
})
r.Run() //listen and serve on 0.0.0.0:8080
}