Skip to content

Instantly share code, notes, and snippets.

@dmigo
Created May 13, 2019 11:33
Show Gist options
  • Save dmigo/88c9b71fceb327ba2dc87bcf83bd3230 to your computer and use it in GitHub Desktop.
Save dmigo/88c9b71fceb327ba2dc87bcf83bd3230 to your computer and use it in GitHub Desktop.
package main
import (
"crypto/rand"
"encoding/base32"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
func generateToken(length int) string {
value := make([]byte, length)
rand.Read(value)
return base32.StdEncoding.EncodeToString(value)
}
func generateTokens(length int, amount int) []string {
tokens := make([]string, amount)
for i := 0; i < amount; i++ {
tokens[i] = generateToken(length)
}
return tokens
}
func getAmount(c *gin.Context) int {
amount, err := strconv.ParseInt(c.DefaultQuery("amount", "1"), 10, 32)
if err != nil {
c.Error(err)
}
return int(amount)
}
func main() {
router := gin.Default()
router.GET("/random", func(c *gin.Context) {
const tokenLength = 4
amount := getAmount(c)
values := generateTokens(tokenLength, amount)
c.JSON(http.StatusOK, gin.H{"values": values})
})
// Listen and serve on 0.0.0.0:8080
router.Run(":8080")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment