-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.go
More file actions
95 lines (87 loc) · 1.98 KB
/
utils.go
File metadata and controls
95 lines (87 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package puff
import (
cryptorand "crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"math/rand/v2"
"mime"
"net/http"
"strings"
)
// RandomNanoID generates a random NanoID with format
// LLLL-NNNN. IMPORTANT: THIS FUNCTION IS NOT
// CRYPTOGRAPHICALLY SECURE. DO NOT USE THIS TO GENERATE
// TOKENS WITH AUTHORITY (instead see RandomToken).
func RandomNanoID() string {
id := ""
for range 4 {
r := rand.IntN(25) + 1
id += fmt.Sprintf("%c", ('A' - 1 + r))
}
id += "-"
for range 4 {
r := rand.IntN(9)
id += fmt.Sprint(r)
}
return id
}
// RandomToken generates a crytographically secure
// random base64 token with the provided length.
func RandomToken(length int) string {
randomBytes := make([]byte, length)
_, err := cryptorand.Read(randomBytes)
if err != nil {
panic(err)
}
return base64.StdEncoding.EncodeToString(randomBytes)
}
func resolveContentType(provided, default_content_type string) string {
if provided == "" {
return default_content_type
}
return provided
}
func resolveStatusCode(provided int, _default int) int {
if provided == 0 {
return _default
}
return provided
}
func contentTypeFromFileName(name string) string {
fileNameSplit := strings.Split(name, ".")
suffix := fileNameSplit[len(fileNameSplit)-1]
ct := mime.TypeByExtension("." + suffix)
if ct == "" {
return "text/plain" // default content type
}
return ct
}
func writeErrorResponse(w http.ResponseWriter, statusCode int, message string) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"error": message})
w.WriteHeader(statusCode)
}
func isAnyOfThese[T comparable](value T, these ...T) bool {
for _, t := range these {
if t == value {
return true
}
}
return false
}
func resolveBool(spec string, def bool) (b bool, err error) {
switch spec {
case "":
b = def
case "true":
b = true
case "false":
b = false
default:
b = def
err = fmt.Errorf("specified boolean on field must be either true or false")
return
}
return
}