-
Notifications
You must be signed in to change notification settings - Fork 7
/
util.go
90 lines (78 loc) · 1.7 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Copyright 2014 Tim Shannon. All rights reserved.
// Use of this source code is governed by the MIT license
// that can be found in the LICENSE file.
package main
import (
"crypto/md5"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
"bitbucket.org/tshannon/freehold/data/store"
"bitbucket.org/tshannon/freehold/resource"
)
func halt(msg string) {
store.Halt()
fmt.Fprintln(os.Stderr, msg)
os.Exit(1)
}
// splitRootAndPath splits the first item in a path from the rest
// /v1/file/test.txt:
// root = "v1"
// path = "/file/test.txt"
func splitRootAndPath(pattern string) (root, path string) {
if pattern == "" {
panic("Invalid pattern")
}
if pattern[:1] == "/" {
pattern = pattern[1:]
}
split := strings.SplitN(pattern, "/", 2)
root = split[0]
if len(split) < 2 {
path = "/"
} else {
path = "/" + split[1]
}
return root, path
}
func checksum(rs io.Reader) string {
buff, err := ioutil.ReadAll(rs)
if err != nil {
halt("Error calculating checksum: " + err.Error())
}
return fmt.Sprintf("%x", md5.Sum(buff))
}
func fileExists(filename string) bool {
if _, err := os.Stat(filename); err == nil {
return true
}
return false
}
func isDir(filename string) bool {
if stat, err := os.Stat(filename); err == nil {
return stat.IsDir()
}
return false
}
func clearEmptyFolder(parent *resource.File) error {
children, err := parent.Children()
if err != nil {
return err
}
if len(children) == 0 {
return os.RemoveAll(parent.Filepath())
}
return nil
}
//ipAddress returns the actual ip address from the request
func ipAddress(r *http.Request) string {
address := r.RemoteAddr
index := strings.LastIndex(address, ":")
if index == -1 {
return address
}
return address[:index]
}