Commit 46b2215ebd14695c0d2bf23dc7a2157ffa2de7c0

Authored by Marko Tikvić
1 parent 6b7121bdf6
Exists in master

lintfix

default_values.go
1 package webutility 1 package webutility
2 2
3 // IntOrDefault ... 3 // IntOrDefault ...
4 func IntOrDefault(v *int) int { 4 func IntOrDefault(v *int) int {
5 if v != nil { 5 if v != nil {
6 return *v 6 return *v
7 } 7 }
8 return 0 8 return 0
9 } 9 }
10 10
11 // Int32OrDefault ... 11 // Int32OrDefault ...
12 func Int32OrDefault(v *int32) int32 { 12 func Int32OrDefault(v *int32) int32 {
13 if v != nil { 13 if v != nil {
14 return *v 14 return *v
15 } 15 }
16 return 0 16 return 0
17 } 17 }
18 18
19 // Int64OrDefault ... 19 // Int64OrDefault ...
20 func Int64OrDefault(v *int64) int64 { 20 func Int64OrDefault(v *int64) int64 {
21 if v != nil { 21 if v != nil {
22 return *v 22 return *v
23 } 23 }
24 return 0 24 return 0
25 } 25 }
26 26
27 // Uint32OrDefault ... 27 // Uint32OrDefault ...
28 func Uint32OrDefault(v *uint32) uint32 { 28 func Uint32OrDefault(v *uint32) uint32 {
29 if v != nil { 29 if v != nil {
30 return *v 30 return *v
31 } 31 }
32 return 0 32 return 0
33 } 33 }
34 34
35 // Uint64OrDefault ... 35 // Uint64OrDefault ...
36 func Uint64OrDefault(v *uint64) uint64 { 36 func Uint64OrDefault(v *uint64) uint64 {
37 if v != nil { 37 if v != nil {
38 return *v 38 return *v
39 } 39 }
40 return 0 40 return 0
41 } 41 }
42 42
43 // StringOrDefault ... 43 // StringOrDefault ...
44 func StringOrDefault(v *string) string { 44 func StringOrDefault(v *string) string {
45 if v != nil { 45 if v != nil {
46 return *v 46 return *v
47 } 47 }
48 return "" 48 return ""
49 } 49 }
50 50
51 // Float32OrDefault ... 51 // Float32OrDefault ...
52 func Float32OrDefault(v *float32) float32 { 52 func Float32OrDefault(v *float32) float32 {
53 if v != nil { 53 if v != nil {
54 return *v 54 return *v
55 } 55 }
56 return 0.0 56 return 0.0
57 } 57 }
58 58
59 // Float64OrDefault ... 59 // Float64OrDefault ...
60 func Float64OrDefault(v *float64) float64 { 60 func Float64OrDefault(v *float64) float64 {
61 if v != nil { 61 if v != nil {
62 return *v 62 return *v
63 } 63 }
64 return 0.0 64 return 0.0
65 } 65 }
66 66
67 // NilSafeInt32OrDefault ...
67 func NilSafeInt32OrDefault(val *interface{}) int32 { 68 func NilSafeInt32OrDefault(val *interface{}) int32 {
68 if *val != nil { 69 if *val != nil {
69 return (*val).(int32) 70 return (*val).(int32)
70 } 71 }
71 return 0 72 return 0
72 } 73 }
73 74
75 // NilSafeInt64OrDefault ...
74 func NilSafeInt64OrDefault(val *interface{}) int64 { 76 func NilSafeInt64OrDefault(val *interface{}) int64 {
75 if *val != nil { 77 if *val != nil {
76 return (*val).(int64) 78 return (*val).(int64)
77 } 79 }
78 return 0 80 return 0
79 } 81 }
80 82
83 // NilSafeUint32OrDefault ...
81 func NilSafeUint32OrDefault(val *interface{}) uint32 { 84 func NilSafeUint32OrDefault(val *interface{}) uint32 {
82 if *val != nil { 85 if *val != nil {
83 return (*val).(uint32) 86 return (*val).(uint32)
84 } 87 }
85 return 0 88 return 0
86 } 89 }
87 90
91 // NilSafeUint64OrDefault ...
88 func NilSafeUint64OrDefault(val *interface{}) uint64 { 92 func NilSafeUint64OrDefault(val *interface{}) uint64 {
89 if *val != nil { 93 if *val != nil {
90 return (*val).(uint64) 94 return (*val).(uint64)
91 } 95 }
92 return 0 96 return 0
93 } 97 }
94 98
99 // NilSafeFloat32OrDefault ...
95 func NilSafeFloat32OrDefault(val *interface{}) float32 { 100 func NilSafeFloat32OrDefault(val *interface{}) float32 {
96 if *val != nil { 101 if *val != nil {
97 return (*val).(float32) 102 return (*val).(float32)
98 } 103 }
99 return 0.0 104 return 0.0
100 } 105 }
101 106
107 // NilSafeFloat64OrDefault ...
102 func NilSafeFloat64OrDefault(val *interface{}) float64 { 108 func NilSafeFloat64OrDefault(val *interface{}) float64 {
103 if *val != nil { 109 if *val != nil {
104 return (*val).(float64) 110 return (*val).(float64)
105 } 111 }
106 return 0.0 112 return 0.0
107 } 113 }
108 114
115 // NilSafeStringOrDefault ...
109 func NilSafeStringOrDefault(val *interface{}) string { 116 func NilSafeStringOrDefault(val *interface{}) string {
110 if *val != nil { 117 if *val != nil {
111 return (*val).(string) 118 return (*val).(string)
112 } 119 }
113 return "" 120 return ""
114 } 121 }
122
115 123
1 package webutility 1 package webutility
2 2
3 import ( 3 import (
4 "bytes" 4 "bytes"
5 "io" 5 "io"
6 "io/ioutil" 6 "io/ioutil"
7 "os" 7 "os"
8 "strings" 8 "strings"
9 ) 9 )
10 10
11 // ReadFileContent ...
11 func ReadFileContent(path string) ([]byte, error) { 12 func ReadFileContent(path string) ([]byte, error) {
12 f, err := os.Open(path) 13 f, err := os.Open(path)
13 if err != nil { 14 if err != nil {
14 return nil, err 15 return nil, err
15 } 16 }
16 defer f.Close() 17 defer f.Close()
17 18
18 buf := &bytes.Buffer{} 19 buf := &bytes.Buffer{}
19 if _, err = io.Copy(buf, f); err != nil { 20 if _, err = io.Copy(buf, f); err != nil {
20 return nil, err 21 return nil, err
21 } 22 }
22 23
23 return buf.Bytes(), nil 24 return buf.Bytes(), nil
24 } 25 }
25 26
26 // ReadFileLines ... 27 // ReadFileLines ...
27 func ReadFileLines(path string) ([]string, error) { 28 func ReadFileLines(path string) ([]string, error) {
28 f, err := os.Open(path) 29 f, err := os.Open(path)
29 if err != nil { 30 if err != nil {
30 return nil, err 31 return nil, err
31 } 32 }
32 defer f.Close() 33 defer f.Close()
33 34
34 var s strings.Builder 35 var s strings.Builder
35 36
36 if _, err = io.Copy(&s, f); err != nil { 37 if _, err = io.Copy(&s, f); err != nil {
37 return nil, err 38 return nil, err
38 } 39 }
39 40
40 lines := strings.Split(s.String(), "\n") 41 lines := strings.Split(s.String(), "\n")
41 for i := range lines { 42 for i := range lines {
42 lines[i] = strings.TrimRight(lines[i], "\r\n") 43 lines[i] = strings.TrimRight(lines[i], "\r\n")
43 } 44 }
44 45
45 return lines, nil 46 return lines, nil
46 } 47 }
47 48
48 // LinesToFile ... 49 // LinesToFile ...
49 func LinesToFile(path string, lines []string) error { 50 func LinesToFile(path string, lines []string) error {
50 content := "" 51 content := ""
51 for _, l := range lines { 52 for _, l := range lines {
52 content += l + "\n" 53 content += l + "\n"
53 } 54 }
54 55
55 return ioutil.WriteFile(path, []byte(content), 0644) // drw-r--r-- 56 return ioutil.WriteFile(path, []byte(content), 0644) // drw-r--r--
56 } 57 }
57 58
58 // InsertLine ... 59 // InsertLine ...
59 func InsertLine(lines *[]string, pos int64, l string) { 60 func InsertLine(lines *[]string, pos int64, l string) {
60 tail := append([]string{l}, (*lines)[pos:]...) 61 tail := append([]string{l}, (*lines)[pos:]...)
61 62
62 *lines = append((*lines)[:pos], tail...) 63 *lines = append((*lines)[:pos], tail...)
63 } 64 }
65
64 66
1 package webutility 1 package webutility
2 2
3 import ( 3 import (
4 "encoding/json" 4 "encoding/json"
5 "fmt" 5 "fmt"
6 "net/http" 6 "net/http"
7 ) 7 )
8 8
9 // StatusRecorder ... 9 // StatusRecorder ...
10 type StatusRecorder struct { 10 type StatusRecorder struct {
11 writer http.ResponseWriter 11 writer http.ResponseWriter
12 status int 12 status int
13 size int 13 size int
14 } 14 }
15 15
16 // NewStatusRecorder ... 16 // NewStatusRecorder ...
17 func NewStatusRecorder(w http.ResponseWriter) *StatusRecorder { 17 func NewStatusRecorder(w http.ResponseWriter) *StatusRecorder {
18 return &StatusRecorder{ 18 return &StatusRecorder{
19 writer: w, 19 writer: w,
20 status: 0, 20 status: 0,
21 size: 0, 21 size: 0,
22 } 22 }
23 } 23 }
24 24
25 // WriteHeader is a wrapper http.ResponseWriter interface 25 // WriteHeader is a wrapper http.ResponseWriter interface
26 func (r *StatusRecorder) WriteHeader(code int) { 26 func (r *StatusRecorder) WriteHeader(code int) {
27 r.status = code 27 r.status = code
28 r.writer.WriteHeader(code) 28 r.writer.WriteHeader(code)
29 } 29 }
30 30
31 // Write is a wrapper for http.ResponseWriter interface 31 // Write is a wrapper for http.ResponseWriter interface
32 func (r *StatusRecorder) Write(in []byte) (int, error) { 32 func (r *StatusRecorder) Write(in []byte) (int, error) {
33 r.size = len(in) 33 r.size = len(in)
34 return r.writer.Write(in) 34 return r.writer.Write(in)
35 } 35 }
36 36
37 // Header is a wrapper for http.ResponseWriter interface 37 // Header is a wrapper for http.ResponseWriter interface
38 func (r *StatusRecorder) Header() http.Header { 38 func (r *StatusRecorder) Header() http.Header {
39 return r.writer.Header() 39 return r.writer.Header()
40 } 40 }
41 41
42 // Status ... 42 // Status ...
43 func (r *StatusRecorder) Status() int { 43 func (r *StatusRecorder) Status() int {
44 return r.status 44 return r.status
45 } 45 }
46 46
47 // Size ... 47 // Size ...
48 func (r *StatusRecorder) Size() int { 48 func (r *StatusRecorder) Size() int {
49 return r.size 49 return r.size
50 } 50 }
51 51
52 // NotFoundHandlerFunc writes HTTP error 404 to w. 52 // NotFoundHandlerFunc writes HTTP error 404 to w.
53 func NotFoundHandlerFunc(w http.ResponseWriter, req *http.Request) { 53 func NotFoundHandlerFunc(w http.ResponseWriter, req *http.Request) {
54 SetDefaultHeaders(w) 54 SetDefaultHeaders(w)
55 if req.Method == "OPTIONS" { 55 if req.Method == "OPTIONS" {
56 return 56 return
57 } 57 }
58 NotFound(w, req, fmt.Sprintf("Resource you requested was not found: %s", req.URL.String())) 58 NotFound(w, req, fmt.Sprintf("Resource you requested was not found: %s", req.URL.String()))
59 } 59 }
60 60
61 // SetContentType ...
61 func SetContentType(w http.ResponseWriter, ctype string) { 62 func SetContentType(w http.ResponseWriter, ctype string) {
62 w.Header().Set("Content-Type", ctype) 63 w.Header().Set("Content-Type", ctype)
63 } 64 }
64 65
66 // SetResponseStatus ...
65 func SetResponseStatus(w http.ResponseWriter, status int) { 67 func SetResponseStatus(w http.ResponseWriter, status int) {
66 w.WriteHeader(status) 68 w.WriteHeader(status)
67 } 69 }
68 70
71 // WriteResponse ...
69 func WriteResponse(w http.ResponseWriter, content []byte) { 72 func WriteResponse(w http.ResponseWriter, content []byte) {
70 w.Write(content) 73 w.Write(content)
71 } 74 }
72 75
73 // SetDefaultHeaders set's default headers for an HTTP response. 76 // SetDefaultHeaders set's default headers for an HTTP response.
74 func SetDefaultHeaders(w http.ResponseWriter) { 77 func SetDefaultHeaders(w http.ResponseWriter) {
75 w.Header().Set("Access-Control-Allow-Origin", "*") 78 w.Header().Set("Access-Control-Allow-Origin", "*")
76 w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS") 79 w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS")
77 w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization") 80 w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
78 SetContentType(w, "application/json; charset=utf-8") 81 SetContentType(w, "application/json; charset=utf-8")
79 } 82 }
80 83
81 // GetLocale ... 84 // GetLocale ...
82 func GetLocale(req *http.Request, dflt string) string { 85 func GetLocale(req *http.Request, dflt string) string {
83 loc := req.FormValue("locale") 86 loc := req.FormValue("locale")
84 if loc == "" { 87 if loc == "" {
85 return dflt 88 return dflt
86 } 89 }
87 return loc 90 return loc
88 } 91 }
89 92
90 // Success ... 93 // Success ...
91 func Success(w http.ResponseWriter, payload interface{}, code int) { 94 func Success(w http.ResponseWriter, payload interface{}, code int) {
92 w.WriteHeader(code) 95 w.WriteHeader(code)
93 if payload != nil { 96 if payload != nil {
94 json.NewEncoder(w).Encode(payload) 97 json.NewEncoder(w).Encode(payload)
95 } 98 }
96 } 99 }
97 100
98 // OK ... 101 // OK ...
99 func OK(w http.ResponseWriter, payload interface{}) { 102 func OK(w http.ResponseWriter, payload interface{}) {
100 Success(w, payload, http.StatusOK) 103 Success(w, payload, http.StatusOK)
101 } 104 }
102 105
103 // Created ... 106 // Created ...
104 func Created(w http.ResponseWriter, payload interface{}) { 107 func Created(w http.ResponseWriter, payload interface{}) {
105 Success(w, payload, http.StatusCreated) 108 Success(w, payload, http.StatusCreated)
106 } 109 }
107 110
108 type weberror struct { 111 type weberror struct {
109 Request string `json:"request"` 112 Request string `json:"request"`
110 Error string `json:"error"` 113 Error string `json:"error"`
111 } 114 }
112 115
113 // Error ... 116 // Error ...
114 func Error(w http.ResponseWriter, r *http.Request, code int, err string) { 117 func Error(w http.ResponseWriter, r *http.Request, code int, err string) {
115 werr := weberror{Error: err, Request: r.Method + " " + r.RequestURI} 118 werr := weberror{Error: err, Request: r.Method + " " + r.RequestURI}
116 w.WriteHeader(code) 119 w.WriteHeader(code)
117 json.NewEncoder(w).Encode(werr) 120 json.NewEncoder(w).Encode(werr)
118 } 121 }
119 122
120 // BadRequest ... 123 // BadRequest ...
121 func BadRequest(w http.ResponseWriter, r *http.Request, err string) { 124 func BadRequest(w http.ResponseWriter, r *http.Request, err string) {
122 Error(w, r, http.StatusBadRequest, err) 125 Error(w, r, http.StatusBadRequest, err)
123 } 126 }
124 127
125 // Unauthorized ... 128 // Unauthorized ...
126 func Unauthorized(w http.ResponseWriter, r *http.Request, err string) { 129 func Unauthorized(w http.ResponseWriter, r *http.Request, err string) {
127 Error(w, r, http.StatusUnauthorized, err) 130 Error(w, r, http.StatusUnauthorized, err)
128 } 131 }
129 132
130 // Forbidden ... 133 // Forbidden ...
131 func Forbidden(w http.ResponseWriter, r *http.Request, err string) { 134 func Forbidden(w http.ResponseWriter, r *http.Request, err string) {
132 Error(w, r, http.StatusForbidden, err) 135 Error(w, r, http.StatusForbidden, err)
133 } 136 }
134 137
135 // NotFound ... 138 // NotFound ...
136 func NotFound(w http.ResponseWriter, r *http.Request, err string) { 139 func NotFound(w http.ResponseWriter, r *http.Request, err string) {
137 Error(w, r, http.StatusNotFound, err) 140 Error(w, r, http.StatusNotFound, err)
138 } 141 }
139 142
140 // Conflict ... 143 // Conflict ...
141 func Conflict(w http.ResponseWriter, r *http.Request, err string) { 144 func Conflict(w http.ResponseWriter, r *http.Request, err string) {
142 Error(w, r, http.StatusConflict, err) 145 Error(w, r, http.StatusConflict, err)
143 } 146 }
144 147
145 // InternalServerError ... 148 // InternalServerError ...
146 func InternalServerError(w http.ResponseWriter, r *http.Request, err string) { 149 func InternalServerError(w http.ResponseWriter, r *http.Request, err string) {
147 Error(w, r, http.StatusInternalServerError, err) 150 Error(w, r, http.StatusInternalServerError, err)
148 } 151 }
152
149 153
1 package webutility 1 package webutility
2 2
3 import ( 3 import (
4 "fmt" 4 "fmt"
5 "strconv" 5 "strconv"
6 "strings" 6 "strings"
7 ) 7 )
8 8
9 const sanitisationPatern = "\"';&*<>=\\`:" 9 const sanitisationPatern = "\"';&*<>=\\`:"
10 10
11 // SanitiseString removes characters from s found in patern and returns new modified string. 11 // SanitiseString removes characters from s found in patern and returns new modified string.
12 func SanitiseString(s string) string { 12 func SanitiseString(s string) string {
13 return ReplaceAny(s, sanitisationPatern, "") 13 return ReplaceAny(s, sanitisationPatern, "")
14 } 14 }
15 15
16 // IsWrappedWith ... 16 // IsWrappedWith ...
17 func IsWrappedWith(src, begin, end string) bool { 17 func IsWrappedWith(src, begin, end string) bool {
18 return strings.HasPrefix(src, begin) && strings.HasSuffix(src, end) 18 return strings.HasPrefix(src, begin) && strings.HasSuffix(src, end)
19 } 19 }
20 20
21 // ParseInt64Arr ... 21 // ParseInt64Arr ...
22 func ParseInt64Arr(s, sep string) (arr []int64) { 22 func ParseInt64Arr(s, sep string) (arr []int64) {
23 s = strings.TrimSpace(s) 23 s = strings.TrimSpace(s)
24 if s != "" { 24 if s != "" {
25 parts := strings.Split(s, sep) 25 parts := strings.Split(s, sep)
26 arr = make([]int64, len(parts)) 26 arr = make([]int64, len(parts))
27 for i, p := range parts { 27 for i, p := range parts {
28 num := StringToInt64(p) 28 num := StringToInt64(p)
29 arr[i] = num 29 arr[i] = num
30 } 30 }
31 } 31 }
32 32
33 return arr 33 return arr
34 } 34 }
35 35
36 // Int64SliceToString ... 36 // Int64SliceToString ...
37 func Int64SliceToString(arr []int64) (s string) { 37 func Int64SliceToString(arr []int64) (s string) {
38 if len(arr) == 0 { 38 if len(arr) == 0 {
39 return "" 39 return ""
40 } 40 }
41 41
42 s += fmt.Sprintf("%d", arr[0]) 42 s += fmt.Sprintf("%d", arr[0])
43 for i := 1; i < len(arr); i++ { 43 for i := 1; i < len(arr); i++ {
44 s += fmt.Sprintf(",%d", arr[i]) 44 s += fmt.Sprintf(",%d", arr[i])
45 } 45 }
46 46
47 return s 47 return s
48 } 48 }
49 49
50 // CombineStrings ... 50 // CombineStrings ...
51 func CombineStrings(s1, s2, s3 string) string { 51 func CombineStrings(s1, s2, s3 string) string {
52 s1 = strings.TrimSpace(s1) 52 s1 = strings.TrimSpace(s1)
53 s2 = strings.TrimSpace(s2) 53 s2 = strings.TrimSpace(s2)
54 54
55 if s1 != "" && s2 != "" { 55 if s1 != "" && s2 != "" {
56 s1 += s3 + s2 56 s1 += s3 + s2
57 } else { 57 } else {
58 s1 += s2 58 s1 += s2
59 } 59 }
60 60
61 return s1 61 return s1
62 } 62 }
63 63
64 // ReplaceAny replaces any of the characters from patern found in s with r and returns a new resulting string. 64 // ReplaceAny replaces any of the characters from patern found in s with r and returns a new resulting string.
65 func ReplaceAny(s, patern, r string) (n string) { 65 func ReplaceAny(s, patern, r string) (n string) {
66 n = s 66 n = s
67 for _, c := range patern { 67 for _, c := range patern {
68 n = strings.Replace(n, string(c), r, -1) 68 n = strings.Replace(n, string(c), r, -1)
69 } 69 }
70 return n 70 return n
71 } 71 }
72 72
73 // StringToBool ...
73 func StringToBool(s string) bool { 74 func StringToBool(s string) bool {
74 res, _ := strconv.ParseBool(s) 75 res, _ := strconv.ParseBool(s)
75 return res 76 return res
76 } 77 }
77 78
79 // BoolToString ...
78 func BoolToString(b bool) string { 80 func BoolToString(b bool) string {
79 return fmt.Sprintf("%b", b) 81 return fmt.Sprintf("%b", b)
80 } 82 }
81 83
84 // StringSliceContains ...
82 func StringSliceContains(slice []string, s string) bool { 85 func StringSliceContains(slice []string, s string) bool {
83 for i := range slice { 86 for i := range slice {
84 if slice[i] == s { 87 if slice[i] == s {
85 return true 88 return true
86 } 89 }
87 } 90 }
88 return false 91 return false
89 } 92 }
90 93
94 // StringAt ...
91 func StringAt(s string, index int) string { 95 func StringAt(s string, index int) string {
92 if len(s)-1 < index || index < 0 { 96 if len(s)-1 < index || index < 0 {
93 return "" 97 return ""
94 } 98 }
95 99
96 return string(s[index]) 100 return string(s[index])
97 } 101 }
98 102
103 // SplitStringAtWholeWords ...
99 func SplitStringAtWholeWords(s string, maxLen int) (res []string) { 104 func SplitStringAtWholeWords(s string, maxLen int) (res []string) {
100 parts := strings.Split(s, " ") 105 parts := strings.Split(s, " ")
101 106
102 res = append(res, parts[0]) 107 res = append(res, parts[0])
103 i := 0 108 i := 0
104 for j := 1; j < len(parts); j++ { 109 for j := 1; j < len(parts); j++ {
105 p := strings.TrimSpace(parts[j]) 110 p := strings.TrimSpace(parts[j])
106 if len(p) > maxLen { 111 if len(p) > maxLen {
107 // TODO(marko): check if maxLen is >= 3 112 // TODO(marko): check if maxLen is >= 3
108 p = p[0 : maxLen-3] 113 p = p[0 : maxLen-3]
109 p += "..." 114 p += "..."
110 } 115 }
111 if len(res[i])+len(p)+1 <= maxLen { 116 if len(res[i])+len(p)+1 <= maxLen {
112 res[i] += " " + p 117 res[i] += " " + p
113 } else { 118 } else {
114 res = append(res, p) 119 res = append(res, p)
115 i++ 120 i++
116 } 121 }
117 } 122 }
118 123
119 return res 124 return res
120 } 125 }
126
121 127