added genString

This commit is contained in:
Brandon Dyck 2020-03-31 06:58:44 -06:00
parent 5f96a929d4
commit e714e66703

View File

@ -1,20 +1,26 @@
package main
import (
"bytes"
"crypto/rand"
"fmt"
"io"
"log"
"math/big"
"net/http"
"time"
h "gitlab.codemonkeysoftware.net/b/hatmill"
a "gitlab.codemonkeysoftware.net/b/hatmill/attribute"
e "gitlab.codemonkeysoftware.net/b/hatmill/element"
"gitlab.codemonkeysoftware.net/b/henwen"
_ "gitlab.codemonkeysoftware.net/b/henwen"
)
const Addr = ":8080"
const Title = "Henwen"
const baseURL = "http://localhost:8080"
const dbFileName = "./henwen.db"
const (
PathRoot = "/"
@ -22,6 +28,8 @@ const (
PathDoCreate = "/create/do"
)
var store *henwen.Store
func writePage(w io.Writer, contents h.Term) error {
page := e.Html()(
e.Head()(
@ -69,9 +77,28 @@ func pageCreate() h.Term {
}
}
func makeAdminURL(eventID, adminCode string) string {
return fmt.Sprintf("%s/%s/admin/%s", baseURL, eventID, adminCode)
}
func pageDoCreate(name string, earliest, latest time.Time) h.Term {
id, err := genString()
if err != nil {
return h.Text(err.Error())
}
adminCode, err := genString()
if err != nil {
return h.Text(err.Error())
}
adminURL := makeAdminURL(id, adminCode)
return h.Terms{
e.H2()(h.Text("Created event!")),
e.P()(
h.Text("You can find it again at "),
e.A(a.Href(adminURL))(h.Text(adminURL)),
h.Text("."),
),
e.H3()(h.Text("Name")),
h.Text(name),
@ -84,6 +111,27 @@ func pageDoCreate(name string, earliest, latest time.Time) h.Term {
}
}
var chars = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func genString() (string, error) {
const length = 10
charsLength := big.NewInt(int64(len(chars)))
var maxN big.Int
maxN.Exp(charsLength, big.NewInt(length), nil)
n, err := rand.Int(rand.Reader, &maxN)
if err != nil {
return "", err
}
var buf bytes.Buffer
for n.Cmp(&big.Int{}) == 1 {
var charIdx big.Int
n.DivMod(n, charsLength, &charIdx)
_ = buf.WriteByte(chars[charIdx.Int64()])
}
return buf.String(), nil
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc(PathRoot, func(w http.ResponseWriter, r *http.Request) {