Files
zineshop/utils/utils.go
2025-06-29 16:57:51 +02:00

61 lines
1.1 KiB
Go

package utils
import (
"bufio"
"crypto/rand"
"encoding/hex"
"io"
"os"
)
func GenerateSessionId(length int) string {
bytes := make([]byte, length) // 16 bytes = 128 bits
_, err := rand.Read(bytes)
if err != nil {
panic("failed to generate session ID")
}
return hex.EncodeToString(bytes)
}
func GenerateToken() string {
return GenerateSessionId(16)
}
const match = "/Page\x00"
// Pages reads the given io.ByteReader until EOF is reached, returning the
// number of pages encountered.
func Pages(reader io.ByteReader) (pages int) {
i := 0
for {
b, err := reader.ReadByte()
if err != nil {
return
}
check:
switch match[i] {
case 0:
if !(b >= 'A' && b <= 'Z' || b >= 'a' && b <= 'z') {
pages++
}
i = 0
goto check
case b:
i++
default:
i = 0
}
}
}
// PagesAtPath opens a PDF file at the given file path, returning the number
// of pages found.
func CountPagesAtPath(path string) (pages int) {
if reader, err := os.Open(path); err == nil {
reader.Chdir()
pages = Pages(bufio.NewReader(reader))
reader.Close()
}
return
}