Skip to content

Commit 4387f80

Browse files
committed
Add utils
1 parent f3bf111 commit 4387f80

File tree

2 files changed

+198
-0
lines changed

2 files changed

+198
-0
lines changed

utils/crypto.go

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package utils
2+
3+
import (
4+
"crypto/rand"
5+
"encoding/base64"
6+
"math"
7+
"math/big"
8+
mathrand "math/rand"
9+
"regexp"
10+
11+
"github.com/dropbox/godropbox/errors"
12+
"github.com/pritunl/pritunl-vault/errortypes"
13+
)
14+
15+
var (
16+
randRe = regexp.MustCompile("[^a-zA-Z0-9]+")
17+
)
18+
19+
func RandStr(n int) (str string, err error) {
20+
for i := 0; i < 10; i++ {
21+
input, e := RandBytes(int(math.Ceil(float64(n) * 1.25)))
22+
if e != nil {
23+
err = e
24+
return
25+
}
26+
27+
output := base64.RawStdEncoding.EncodeToString(input)
28+
output = randRe.ReplaceAllString(output, "")
29+
30+
if len(output) < n {
31+
continue
32+
}
33+
34+
str = output[:n]
35+
break
36+
}
37+
38+
if str == "" {
39+
err = &errortypes.UnknownError{
40+
errors.Wrap(err, "utils: Random generate error"),
41+
}
42+
return
43+
}
44+
45+
return
46+
}
47+
48+
func RandBytes(size int) (bytes []byte, err error) {
49+
bytes = make([]byte, size)
50+
_, err = rand.Read(bytes)
51+
if err != nil {
52+
err = &errortypes.UnknownError{
53+
errors.Wrap(err, "utils: Random read error"),
54+
}
55+
return
56+
}
57+
58+
return
59+
}
60+
61+
func init() {
62+
n, err := rand.Int(rand.Reader, big.NewInt(9223372036854775806))
63+
if err != nil {
64+
panic(err)
65+
}
66+
67+
mathrand.Seed(n.Int64())
68+
}

utils/request.go

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
package utils
2+
3+
import (
4+
"fmt"
5+
"io"
6+
"net/http"
7+
"strings"
8+
9+
"github.com/gin-gonic/gin"
10+
"github.com/gin-gonic/gin/render"
11+
)
12+
13+
type NopCloser struct {
14+
io.Reader
15+
}
16+
17+
func (NopCloser) Close() error {
18+
return nil
19+
}
20+
21+
var httpErrCodes = map[int]string{
22+
400: "Bad Request",
23+
401: "Unauthorized",
24+
402: "Payment Required",
25+
403: "Forbidden",
26+
404: "Not Found",
27+
405: "Method Not Allowed",
28+
406: "Not Acceptable",
29+
407: "Proxy Authentication Required",
30+
408: "Request Timeout",
31+
409: "Conflict",
32+
410: "Gone",
33+
411: "Length Required",
34+
412: "Precondition Failed",
35+
413: "Payload Too Large",
36+
414: "URI Too Long",
37+
415: "Unsupported Media Type",
38+
416: "Range Not Satisfiable",
39+
417: "Expectation Failed",
40+
421: "Misdirected Request",
41+
422: "Unprocessable Entity",
42+
423: "Locked",
43+
424: "Failed Dependency",
44+
426: "Upgrade Required",
45+
428: "Precondition Required",
46+
429: "Too Many Requests",
47+
431: "Request Header Fields Too Large",
48+
451: "Unavailable For Legal Reasons",
49+
500: "Internal Server Error",
50+
501: "Not Implemented",
51+
502: "Bad Gateway",
52+
503: "Service Unavailable",
53+
504: "Gateway Timeout",
54+
505: "HTTP Version Not Supported",
55+
506: "Variant Also Negotiates",
56+
507: "Insufficient Storage",
57+
508: "Loop Detected",
58+
510: "Not Extended",
59+
511: "Network Authentication Required",
60+
}
61+
62+
func StripPort(hostport string) string {
63+
colon := strings.IndexByte(hostport, ':')
64+
if colon == -1 {
65+
return hostport
66+
}
67+
if i := strings.IndexByte(hostport, ']'); i != -1 {
68+
return strings.TrimPrefix(hostport[:i], "[")
69+
}
70+
return hostport[:colon]
71+
}
72+
73+
func FormatHostPort(hostname string, port int) string {
74+
if strings.Contains(hostname, ":") {
75+
hostname = "[" + hostname + "]"
76+
}
77+
return fmt.Sprintf("%s:%d", hostname, port)
78+
}
79+
80+
func GetStatusMessage(code int) string {
81+
return fmt.Sprintf("%d %s", code, http.StatusText(code))
82+
}
83+
84+
func AbortWithStatus(c *gin.Context, code int) {
85+
r := render.String{
86+
Format: GetStatusMessage(code),
87+
}
88+
89+
c.Status(code)
90+
r.WriteContentType(c.Writer)
91+
c.Writer.WriteHeaderNow()
92+
r.Render(c.Writer)
93+
c.Abort()
94+
}
95+
96+
func AbortWithError(c *gin.Context, code int, err error) {
97+
AbortWithStatus(c, code)
98+
c.Error(err)
99+
}
100+
101+
func WriteStatus(w http.ResponseWriter, code int) {
102+
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
103+
w.Header().Set("X-Content-Type-Options", "nosniff")
104+
w.WriteHeader(code)
105+
fmt.Fprintln(w, GetStatusMessage(code))
106+
}
107+
108+
func WriteText(w http.ResponseWriter, code int, text string) {
109+
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
110+
w.Header().Set("X-Content-Type-Options", "nosniff")
111+
w.WriteHeader(code)
112+
fmt.Fprintln(w, text)
113+
}
114+
115+
func WriteUnauthorized(w http.ResponseWriter, msg string) {
116+
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
117+
w.Header().Set("X-Content-Type-Options", "nosniff")
118+
w.WriteHeader(401)
119+
fmt.Fprintln(w, "401 "+msg)
120+
}
121+
122+
func CloneHeader(src http.Header) (dst http.Header) {
123+
dst = make(http.Header, len(src))
124+
for k, vv := range src {
125+
vv2 := make([]string, len(vv))
126+
copy(vv2, vv)
127+
dst[k] = vv2
128+
}
129+
return dst
130+
}

0 commit comments

Comments
 (0)