-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
71 lines (62 loc) · 1.69 KB
/
util.go
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
package util
import (
"io/fs"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
"time"
"github.com/pkg/errors"
)
// FileWalkerFunc walker function for WalkFiles
type FileWalkerFunc func(data []byte, filePath string) error
// WalkFiles is wrapper around fs.Walk that walks only files excluding directories
// and handles file one errors
func WalkFiles(hfs fs.FS, prefixPath string, walker FileWalkerFunc) error {
walkErr := fs.WalkDir(hfs, prefixPath, func(filePath string, d fs.DirEntry, err error) error {
if err != nil {
return errors.Wrapf(err, "fs walk error")
}
if d.IsDir() {
return nil
}
f, err := hfs.Open(filePath)
if err != nil {
return errors.Wrapf(err, "wrong filepath: %q", filePath)
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return errors.Wrapf(err, "read error for %q", filePath)
}
subPath := strings.TrimPrefix(filePath, prefixPath+"/")
err = walker(data, subPath)
if err != nil {
return err
}
return nil
})
return walkErr
}
// AddRoutePrefix adds prefix to request and handle with h handler
func AddRoutePrefix(prefix string, h http.HandlerFunc) http.Handler {
if strings.ContainsAny(prefix, "{}") {
panic("prefix path not permit URL parameters slashes.")
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r2 := new(http.Request)
*r2 = *r
r2.URL = new(url.URL)
*r2.URL = *r.URL
r2.URL.Path = prefix + r2.URL.Path
h.ServeHTTP(w, r2)
})
}
// ExecTimeLogger returns function intented to be used in defer to log execution time
func ExecTimeLogger(msg string) func() {
startTime := time.Now()
return func() {
log.Printf("%s in %dms", msg, time.Since(startTime).Milliseconds())
}
}