Commit 707782344fd94987d3cd7c8426d674dd6d7b16a1

Authored by Marko Tikvić
1 parent 954ce8ddd9
Exists in master

lint; vet

... ... @@ -29,6 +29,7 @@ type TokenClaims struct {
29 29 ExpiresIn int64 `json:"expires_in"`
30 30 }
31 31  
  32 +// InitJWT ...
32 33 func InitJWT(issuer, secret string) {
33 34 _issuer = issuer
34 35 _secret = secret
... ... @@ -130,6 +131,7 @@ func RefreshAuthToken(tok string) (TokenClaims, error) {
130 131 return CreateAuthToken(claims.Username, claims.RoleName, claims.RoleID)
131 132 }
132 133  
  134 +// AuthCheck ...
133 135 func AuthCheck(req *http.Request, roles string) (*TokenClaims, error) {
134 136 // validate token and check expiration date
135 137 claims, err := GetTokenClaims(req)
... ... @@ -151,7 +153,7 @@ func AuthCheck(req *http.Request, roles string) (*TokenClaims, error) {
151 153 }
152 154  
153 155 parts := strings.Split(roles, ",")
154   - for i, _ := range parts {
  156 + for i := range parts {
155 157 r := strings.Trim(parts[i], " ")
156 158 if claims.RoleName == r {
157 159 return claims, nil
... ...
default_values.go
1 1 package webutility
2 2  
  3 +// Int32ValueOrDefault ...
3 4 func Int32ValueOrDefault(val *interface{}) (def int32) {
4 5 if *val != nil {
5 6 def = (*val).(int32)
... ... @@ -7,6 +8,7 @@ func Int32ValueOrDefault(val *interface{}) (def int32) {
7 8 return def
8 9 }
9 10  
  11 +// Int64ValueOrDefault ...
10 12 func Int64ValueOrDefault(val *interface{}) (def int64) {
11 13 if *val != nil {
12 14 def = (*val).(int64)
... ... @@ -14,6 +16,7 @@ func Int64ValueOrDefault(val *interface{}) (def int64) {
14 16 return def
15 17 }
16 18  
  19 +// Uint32ValueOrDefault ...
17 20 func Uint32ValueOrDefault(val *interface{}) (def uint32) {
18 21 if *val != nil {
19 22 def = (*val).(uint32)
... ... @@ -21,6 +24,7 @@ func Uint32ValueOrDefault(val *interface{}) (def uint32) {
21 24 return def
22 25 }
23 26  
  27 +// Uint64ValueOrDefault ...
24 28 func Uint64ValueOrDefault(val *interface{}) (def uint64) {
25 29 if *val != nil {
26 30 def = (*val).(uint64)
... ... @@ -28,6 +32,7 @@ func Uint64ValueOrDefault(val *interface{}) (def uint64) {
28 32 return def
29 33 }
30 34  
  35 +// Float32ValueOrDefault ...
31 36 func Float32ValueOrDefault(val *interface{}) (def float32) {
32 37 if *val != nil {
33 38 def = (*val).(float32)
... ... @@ -35,6 +40,7 @@ func Float32ValueOrDefault(val *interface{}) (def float32) {
35 40 return def
36 41 }
37 42  
  43 +// Float64ValueOrDefault ...
38 44 func Float64ValueOrDefault(val *interface{}) (def float64) {
39 45 if *val != nil {
40 46 return (*val).(float64)
... ... @@ -42,9 +48,11 @@ func Float64ValueOrDefault(val *interface{}) (def float64) {
42 48 return def
43 49 }
44 50  
  51 +// StringValueOrDefault ...
45 52 func StringValueOrDefault(val *interface{}) (def string) {
46 53 if *val != nil {
47 54 def = (*val).(string)
48 55 }
49 56 return def
50 57 }
  58 +
... ...
... ... @@ -10,76 +10,100 @@ import (
10 10 "strings"
11 11 )
12 12  
  13 +// Email ...
13 14 type Email struct {
14   - To []string
15   - From string
16   - Subject string
17   - Body string
  15 + recipients []string
  16 + sender string
  17 + subject string
  18 + body string
18 19  
19 20 config *EmailConfig
20 21 }
21 22  
  23 +// NewEmail ...
22 24 func NewEmail() *Email {
23   - return &Email{
24   - To: nil,
25   - From: "",
26   - Subject: "",
27   - Body: "",
28   - config: nil,
  25 + return new(Email)
  26 +}
  27 +
  28 +// EmailConfig ...
  29 +type EmailConfig struct {
  30 + ServerName string `json:"-"`
  31 + Identity string `json:"-"`
  32 + Username string `json:"username"`
  33 + Password string `json:"password"`
  34 + Host string `json:"host"`
  35 + Port int `json:"port"`
  36 +}
  37 +
  38 +// NewEmailConfig ...
  39 +func NewEmailConfig(ident, uname, pword, host string, port int) *EmailConfig {
  40 + return &EmailConfig{
  41 + ServerName: host + fmt.Sprintf(":%d", port),
  42 + Identity: ident,
  43 + Username: uname,
  44 + Password: pword,
  45 + Host: host,
  46 + Port: port,
29 47 }
30 48 }
31 49  
  50 +// Config ...
32 51 func (e *Email) Config(cfg *EmailConfig) {
33 52 e.config = cfg
34 53 }
35 54  
36   -func (e *Email) SetFrom(from string) {
37   - e.From = from
  55 +// Sender ...
  56 +func (e *Email) Sender(from string) {
  57 + e.sender = from
38 58 }
39 59  
40   -func (e *Email) SetTo(to []string) {
41   - e.To = to
  60 +// AddRecipient ...
  61 +func (e *Email) AddRecipient(r string) {
  62 + e.recipients = append(e.recipients, r)
42 63 }
43 64  
44   -func (e *Email) SetSubject(sub string) {
45   - e.Subject = sub
  65 +// Subject ...
  66 +func (e *Email) Subject(sub string) {
  67 + e.subject = sub
46 68 }
47 69  
48   -func (e *Email) SetBody(body string) {
49   - e.Body = body
  70 +func (e *Email) Write(body string) {
  71 + e.body = body
50 72 }
51 73  
52 74 func (e *Email) String() string {
53 75 var str strings.Builder
54 76  
55   - str.WriteString("From:" + e.From + "\r\n")
  77 + str.WriteString("From:" + e.sender + "\r\n")
56 78  
57 79 str.WriteString("To:")
58   - for i, _ := range e.To {
  80 + for i := range e.recipients {
59 81 if i > 0 {
60 82 str.WriteString(",")
61 83 }
62   - str.WriteString(e.To[i])
  84 + str.WriteString(e.recipients[i])
63 85 }
64 86 str.WriteString("\r\n")
65 87  
66   - str.WriteString("Subject:" + e.Subject + "\r\n")
  88 + str.WriteString("Subject:" + e.subject + "\r\n")
67 89  
68 90 // body
69   - str.WriteString("\r\n" + e.Body + "\r\n")
  91 + str.WriteString("\r\n" + e.body + "\r\n")
70 92  
71 93 return str.String()
72 94 }
73 95  
  96 +// Bytes ...
74 97 func (e *Email) Bytes() []byte {
75 98 return []byte(e.String())
76 99 }
77 100  
78   -func (email *Email) Send() error {
79   - if email.config == nil {
  101 +// Send ...
  102 +func (e *Email) Send() error {
  103 + if e.config == nil {
80 104 return errors.New("email configuration not provided")
81 105 }
82   - conf := email.config
  106 + conf := e.config
83 107  
84 108 c, err := smtp.Dial(conf.ServerName)
85 109 if err != nil {
... ... @@ -87,10 +111,12 @@ func (email *Email) Send() error {
87 111 }
88 112 defer c.Close()
89 113  
90   - // not sure if this is needed
91   - //if err = c.Hello(conf.ServerName); err != nil {
92   - // return err
93   - //}
  114 + /*
  115 + // not sure if this is needed
  116 + if err = c.Hello(conf.ServerName); err != nil {
  117 + return err
  118 + }
  119 + */
94 120  
95 121 if ok, _ := c.Extension("STARTTLS"); ok {
96 122 // disable stupid tls check for self-signed certificates
... ... @@ -98,10 +124,12 @@ func (email *Email) Send() error {
98 124 ServerName: conf.ServerName,
99 125 InsecureSkipVerify: true,
100 126 }
101   - // for golang testing
102   - //if testHookStartTLS != nil {
103   - // testHookStartTLS(config)
104   - //}
  127 + /*
  128 + // for golang testing
  129 + if testHookStartTLS != nil {
  130 + testHookStartTLS(config)
  131 + }
  132 + */
105 133 if err = c.StartTLS(config); err != nil {
106 134 return err
107 135 }
... ... @@ -125,11 +153,11 @@ func (email *Email) Send() error {
125 153 return err
126 154 }
127 155  
128   - if err = c.Mail(email.From); err != nil {
  156 + if err = c.Mail(e.sender); err != nil {
129 157 return err
130 158 }
131 159  
132   - for _, addr := range email.To {
  160 + for _, addr := range e.recipients {
133 161 if err = c.Rcpt(addr); err != nil {
134 162 return err
135 163 }
... ... @@ -140,7 +168,7 @@ func (email *Email) Send() error {
140 168 return err
141 169 }
142 170  
143   - _, err = w.Write(email.Bytes())
  171 + _, err = w.Write(e.Bytes())
144 172 if err != nil {
145 173 return err
146 174 }
... ... @@ -152,23 +180,3 @@ func (email *Email) Send() error {
152 180  
153 181 return c.Quit()
154 182 }
155   -
156   -type EmailConfig struct {
157   - ServerName string `json:"-"`
158   - Identity string `json:"-"`
159   - Username string `json:"username"`
160   - Password string `json:"password"`
161   - Host string `json:"host"`
162   - Port int `json:"port"`
163   -}
164   -
165   -func NewEmailConfig(ident, uname, pword, host string, port int) *EmailConfig {
166   - return &EmailConfig{
167   - ServerName: host + fmt.Sprintf(":%d", port),
168   - Identity: ident,
169   - Username: uname,
170   - Password: pword,
171   - Host: host,
172   - Port: port,
173   - }
174   -}
... ...
... ... @@ -7,21 +7,26 @@ import (
7 7 "strings"
8 8 )
9 9  
  10 +// Filter ...
10 11 type Filter map[string][]string
11 12  
  13 +// Get ...
12 14 func (f Filter) Get(key string) (values []string, ok bool) {
13 15 values, ok = f[key]
14 16 return values, ok
15 17 }
16 18  
  19 +// Count ...
17 20 func (f Filter) Count() int {
18 21 return len(f)
19 22 }
20 23  
  24 +// Add ...
21 25 func (f Filter) Add(key, val string) {
22 26 f[key] = append(f[key], val)
23 27 }
24 28  
  29 +// ValueAt ...
25 30 func (f Filter) ValueAt(val string, index int) string {
26 31 if filter, ok := f[val]; ok {
27 32 if len(filter) > index {
... ... @@ -32,15 +37,15 @@ func (f Filter) ValueAt(val string, index int) string {
32 37 return ""
33 38 }
34 39  
35   -func (fs Filter) validate(validFilters []string) (Filter, bool) {
  40 +func (f Filter) validate(validFilters []string) (Filter, bool) {
36 41 goodFilters := make(Filter)
37 42 cnt, len := 0, 0
38   - for f, _ := range fs {
  43 + for fi := range f {
39 44 len++
40 45 for _, v := range validFilters {
41   - if f == v {
  46 + if fi == v {
42 47 cnt++
43   - goodFilters[f] = fs[f]
  48 + goodFilters[fi] = f[fi]
44 49 }
45 50 }
46 51 }
... ... @@ -54,14 +59,14 @@ func (fs Filter) validate(validFilters []string) (Filter, bool) {
54 59 return goodFilters, result
55 60 }
56 61  
57   -// requires input in format: "param1::value1|param2::value2..."
  62 +// ParseFilters requires input in format: "param1::value1|param2::value2..."
58 63 func ParseFilters(req *http.Request, header string) (filters Filter) {
59 64 q := req.FormValue(header)
60 65 q = strings.Trim(q, "\"")
61 66 kvp := strings.Split(q, "|")
62 67 filters = make(Filter, len(kvp))
63 68  
64   - for i, _ := range kvp {
  69 + for i := range kvp {
65 70 kv := strings.Split(kvp[i], "::")
66 71 if len(kv) == 2 {
67 72 key, _ := url.QueryUnescape(kv[0])
... ... @@ -78,7 +83,8 @@ func ParseFilters(req *http.Request, header string) (filters Filter) {
78 83 return filters
79 84 }
80 85  
81   -// TODO(marko): very dodgy, needs more robustness
  86 +// MakeFilterString is very dodgy, needs more robustness.
  87 +// TODO(marko)
82 88 func MakeFilterString(prefix string, filters Filter, validFilters []string) (res string, ok bool) {
83 89 if prefix != "" {
84 90 prefix += "."
... ...
... ... @@ -33,6 +33,7 @@ func EqualQuotes(stmt string) string {
33 33 return stmt
34 34 }
35 35  
  36 +// EqualString ...
36 37 func EqualString(stmt string) string {
37 38 if stmt != "" {
38 39 stmt = fmt.Sprintf(" = %s", stmt)
... ... @@ -48,3 +49,4 @@ func LikeQuotes(stmt string) string {
48 49 }
49 50 return stmt
50 51 }
  52 +
... ...
... ... @@ -6,12 +6,14 @@ import (
6 6 "net/http"
7 7 )
8 8  
  9 +// StatusRecorder ...
9 10 type StatusRecorder struct {
10 11 writer http.ResponseWriter
11 12 status int
12 13 size int
13 14 }
14 15  
  16 +// NewStatusRecorder ...
15 17 func NewStatusRecorder(w http.ResponseWriter) *StatusRecorder {
16 18 return &StatusRecorder{
17 19 writer: w,
... ... @@ -20,27 +22,29 @@ func NewStatusRecorder(w http.ResponseWriter) *StatusRecorder {
20 22 }
21 23 }
22 24  
23   -// http.ResponseWriter interface
  25 +// WriteHeader is a wrapper http.ResponseWriter interface
24 26 func (r *StatusRecorder) WriteHeader(code int) {
25 27 r.status = code
26 28 r.writer.WriteHeader(code)
27 29 }
28 30  
29   -// http.ResponseWriter interface
  31 +// Write is a wrapper for http.ResponseWriter interface
30 32 func (r *StatusRecorder) Write(in []byte) (int, error) {
31 33 r.size = len(in)
32 34 return r.writer.Write(in)
33 35 }
34 36  
35   -// http.ResponseWriter interface
  37 +// Header is a wrapper for http.ResponseWriter interface
36 38 func (r *StatusRecorder) Header() http.Header {
37 39 return r.writer.Header()
38 40 }
39 41  
  42 +// Status ...
40 43 func (r *StatusRecorder) Status() int {
41 44 return r.status
42 45 }
43 46  
  47 +// Size ...
44 48 func (r *StatusRecorder) Size() int {
45 49 return r.size
46 50 }
... ... @@ -62,6 +66,7 @@ func SetDefaultHeaders(w http.ResponseWriter) {
62 66 w.Header().Set("Content-Type", "application/json; charset=utf-8")
63 67 }
64 68  
  69 +// GetLocale ...
65 70 func GetLocale(req *http.Request, dflt string) string {
66 71 loc := req.FormValue("locale")
67 72 if loc == "" {
... ... @@ -70,7 +75,7 @@ func GetLocale(req *http.Request, dflt string) string {
70 75 return loc
71 76 }
72 77  
73   -// 2xx
  78 +// Success ...
74 79 func Success(w http.ResponseWriter, payload interface{}, code int) {
75 80 w.WriteHeader(code)
76 81 if payload != nil {
... ... @@ -78,12 +83,12 @@ func Success(w http.ResponseWriter, payload interface{}, code int) {
78 83 }
79 84 }
80 85  
81   -// 200
  86 +// OK ...
82 87 func OK(w http.ResponseWriter, payload interface{}) {
83 88 Success(w, payload, http.StatusOK)
84 89 }
85 90  
86   -// 201
  91 +// Created ...
87 92 func Created(w http.ResponseWriter, payload interface{}) {
88 93 Success(w, payload, http.StatusCreated)
89 94 }
... ... @@ -93,39 +98,40 @@ type weberror struct {
93 98 Error string `json:"error"`
94 99 }
95 100  
96   -// 4xx; 5xx
  101 +// Error ...
97 102 func Error(w http.ResponseWriter, r *http.Request, code int, err string) {
98 103 werr := weberror{Error: err, Request: r.Method + " " + r.RequestURI}
99 104 w.WriteHeader(code)
100 105 json.NewEncoder(w).Encode(werr)
101 106 }
102 107  
103   -// 400
  108 +// BadRequest ...
104 109 func BadRequest(w http.ResponseWriter, r *http.Request, err string) {
105 110 Error(w, r, http.StatusBadRequest, err)
106 111 }
107 112  
108   -// 401
  113 +// Unauthorized ...
109 114 func Unauthorized(w http.ResponseWriter, r *http.Request, err string) {
110 115 Error(w, r, http.StatusUnauthorized, err)
111 116 }
112 117  
113   -// 403
  118 +// Forbidden ...
114 119 func Forbidden(w http.ResponseWriter, r *http.Request, err string) {
115 120 Error(w, r, http.StatusForbidden, err)
116 121 }
117 122  
118   -// 404
  123 +// NotFound ...
119 124 func NotFound(w http.ResponseWriter, r *http.Request, err string) {
120 125 Error(w, r, http.StatusNotFound, err)
121 126 }
122 127  
123   -// 409
  128 +// Conflict ...
124 129 func Conflict(w http.ResponseWriter, r *http.Request, err string) {
125 130 Error(w, r, http.StatusConflict, err)
126 131 }
127 132  
128   -// 500
  133 +// InternalServerError ...
129 134 func InternalServerError(w http.ResponseWriter, r *http.Request, err string) {
130 135 Error(w, r, http.StatusInternalServerError, err)
131 136 }
  137 +
... ...
... ... @@ -5,6 +5,7 @@ import (
5 5 "fmt"
6 6 )
7 7  
  8 +// ListOptions ...
8 9 type ListOptions struct {
9 10 GlobalFilter bool `json:"globalFilter"`
10 11 LocalFilters bool `json:"localFilters"`
... ... @@ -16,6 +17,7 @@ type ListOptions struct {
16 17 Total bool `json:"total"`
17 18 }
18 19  
  20 +// ListFilter ...
19 21 type ListFilter struct {
20 22 Position uint32 `json:"-"`
21 23 ObjectType string `json:"-"`
... ... @@ -26,6 +28,7 @@ type ListFilter struct {
26 28 DropdownConfig Dropdown `json:"dropdownConfig"`
27 29 }
28 30  
  31 +// Dropdown ...
29 32 type Dropdown struct {
30 33 ObjectType string `json:"objectType"`
31 34 FiltersField string `json:"filtersField"`
... ... @@ -33,6 +36,7 @@ type Dropdown struct {
33 36 LabelField string `json:"labelField"`
34 37 }
35 38  
  39 +// ListGraph ...
36 40 type ListGraph struct {
37 41 ObjectType string `json:"objectType"`
38 42 X string `json:"xField"`
... ... @@ -41,6 +45,7 @@ type ListGraph struct {
41 45 Label string `json:"label"`
42 46 }
43 47  
  48 +// ListActions ...
44 49 type ListActions struct {
45 50 Create bool `json:"create"`
46 51 Update bool `json:"update"`
... ... @@ -53,6 +58,7 @@ type ListActions struct {
53 58 ShowFile bool `json:"showFile"`
54 59 }
55 60  
  61 +// ListNavNode ...
56 62 type ListNavNode struct {
57 63 ObjectType string `json:"objectType"`
58 64 LabelField string `json:"label"`
... ... @@ -62,12 +68,14 @@ type ListNavNode struct {
62 68 ParentFilterField string `json:"parentFilterField"`
63 69 }
64 70  
  71 +// ListParentNode ...
65 72 type ListParentNode struct {
66 73 ObjectType string `json:"objectType"`
67 74 LabelField string `json:"labelField"`
68 75 FilterField string `json:"filterField"`
69 76 }
70 77  
  78 +// ListPivot ...
71 79 type ListPivot struct {
72 80 ObjectType string `json:"objectType"`
73 81 GroupField string `json:"groupField"`
... ... @@ -75,6 +83,7 @@ type ListPivot struct {
75 83 Value string `json:"valueField"`
76 84 }
77 85  
  86 +// ListDetails ...
78 87 type ListDetails struct {
79 88 ObjectType string `json:"objectType"`
80 89 ParentObjectType string `json:"parentObjectType"`
... ... @@ -82,12 +91,14 @@ type ListDetails struct {
82 91 SingleDetail bool `json:"singleDetail"`
83 92 }
84 93  
  94 +// ListLiveGraph ...
85 95 type ListLiveGraph struct {
86 96 ObjectType string `json:"objectType"`
87 97 ValueFields string `json:"valueFields"`
88 98 LabelFields string `json:"labelFields"`
89 99 }
90 100  
  101 +// ListConfig ...
91 102 type ListConfig struct {
92 103 ObjectType string `json:"objectType"`
93 104 Title string `json:"title"`
... ... @@ -152,7 +163,7 @@ func GetListConfigObjectIDField(db *sql.DB, otype string) string {
152 163 return resp
153 164 }
154 165  
155   -// newDefaultList returns default configuration for the provided object type.
  166 +// NewListConfig returns default configuration for the provided object type.
156 167 func NewListConfig(objType string) ListConfig {
157 168 list := ListConfig{
158 169 ObjectType: objType,
... ... @@ -182,7 +193,7 @@ func NewListConfig(objType string) ListConfig {
182 193 return list
183 194 }
184 195  
185   -// setListParams sets the default parameters of the provided configuration list for the provided object type.
  196 +// setParams sets the default parameters of the provided configuration list for the provided object type.
186 197 func (list *ListConfig) setParams(db *sql.DB, objType string) error {
187 198 rows, err := db.Query(`SELECT
188 199 OBJECT_TYPE,
... ... @@ -215,7 +226,7 @@ func (list *ListConfig) setParams(db *sql.DB, objType string) error {
215 226 return nil
216 227 }
217 228  
218   -// ListNavigation returns list navigation node slice for the provided objectType.
  229 +// SetNavigation returns set's navigation nodes for listObjType object type.
219 230 func (list *ListConfig) SetNavigation(db *sql.DB, listObjType string) error {
220 231 list.Navigation = make([]ListNavNode, 0)
221 232 rows, err := db.Query(`SELECT
... ... @@ -247,7 +258,7 @@ func (list *ListConfig) SetNavigation(db *sql.DB, listObjType string) error {
247 258 return nil
248 259 }
249 260  
250   -// getListActions returns list actions for the provided object type.
  261 +// SetActions sets list's actions based for objType object type.
251 262 func (list *ListConfig) SetActions(db *sql.DB, objType string) error {
252 263 rows, err := db.Query(`SELECT
253 264 ACTION_CREATE,
... ... @@ -286,7 +297,7 @@ func (list *ListConfig) SetActions(db *sql.DB, objType string) error {
286 297 return nil
287 298 }
288 299  
289   -// getListFiters returns list filter slice for the provided object type.
  300 +// SetFilters ...
290 301 func (list *ListConfig) SetFilters(db *sql.DB, objType string) error {
291 302 list.Filters = make([]ListFilter, 0)
292 303 filtersFields, err := list.GetFilterFieldsAndPosition(db, objType)
... ... @@ -294,7 +305,7 @@ func (list *ListConfig) SetFilters(db *sql.DB, objType string) error {
294 305 return err
295 306 }
296 307 for field, pos := range filtersFields {
297   - filters, _ := list.GetFiltersByFilterField(db, field)
  308 + filters, _ := list.getFiltersByFilterField(db, field)
298 309 for _, filter := range filters {
299 310 var f ListFilter
300 311 f.Position = pos
... ... @@ -318,7 +329,7 @@ func (list *ListConfig) SetFilters(db *sql.DB, objType string) error {
318 329 return nil
319 330 }
320 331  
321   -// getFilterFieldsAndPosition returns a map of filter fields and their respective position in the menu.
  332 +// GetFilterFieldsAndPosition returns a map of filter fields and their respective position in the menu.
322 333 func (list *ListConfig) GetFilterFieldsAndPosition(db *sql.DB, objType string) (map[string]uint32, error) {
323 334 filtersField := make(map[string]uint32, 0)
324 335 rows, err := db.Query(`SELECT
... ... @@ -349,8 +360,8 @@ type _filter struct {
349 360 Type string
350 361 }
351 362  
352   -// getFiltersByFilterField returns filter slice for the provided filter field.
353   -func (list *ListConfig) GetFiltersByFilterField(db *sql.DB, filtersField string) ([]_filter, error) {
  363 +// getFiltersByFilterField ...
  364 +func (list *ListConfig) getFiltersByFilterField(db *sql.DB, filtersField string) ([]_filter, error) {
354 365 resp := make([]_filter, 0)
355 366 rows, err := db.Query(`SELECT
356 367 FILTERS_TYPE,
... ... @@ -374,7 +385,7 @@ func (list *ListConfig) GetFiltersByFilterField(db *sql.DB, filtersField string)
374 385 return resp, nil
375 386 }
376 387  
377   -// getFilterDropdownConfig returns dropdown menu for the provided filter field.
  388 +// SetDropdownConfig ...
378 389 func (f *ListFilter) SetDropdownConfig(db *sql.DB, filtersField string) error {
379 390 var resp Dropdown
380 391 rows, err := db.Query(`SELECT
... ... @@ -417,7 +428,7 @@ func (list *ListConfig) sortFilters() {
417 428 }
418 429 }
419 430  
420   -// getListGraph return list graph slice for the provided object type.
  431 +// SetGraph ...
421 432 func (list *ListConfig) SetGraph(db *sql.DB, objType string) error {
422 433 list.Graphs = make([]ListGraph, 0)
423 434 rows, err := db.Query(`SELECT
... ... @@ -445,7 +456,7 @@ func (list *ListConfig) SetGraph(db *sql.DB, objType string) error {
445 456 return nil
446 457 }
447 458  
448   -// getListOptions returns list options for the provided object type.
  459 +// SetOptions ...
449 460 func (list *ListConfig) SetOptions(db *sql.DB, objType string) error {
450 461 rows, err := db.Query(`SELECT
451 462 GLOBAL_FILTER,
... ... @@ -482,7 +493,7 @@ func (list *ListConfig) SetOptions(db *sql.DB, objType string) error {
482 493 return nil
483 494 }
484 495  
485   -// getListParent returns list parent node slice for the provided object type.
  496 +// SetParent ...
486 497 func (list *ListConfig) SetParent(db *sql.DB, objType string) error {
487 498 list.Parent = make([]ListParentNode, 0)
488 499 rows, err := db.Query(`SELECT
... ... @@ -508,7 +519,7 @@ func (list *ListConfig) SetParent(db *sql.DB, objType string) error {
508 519 return nil
509 520 }
510 521  
511   -// getListPivot list pivot slice for the provided object type.
  522 +// SetPivot ...
512 523 func (list *ListConfig) SetPivot(db *sql.DB, objType string) error {
513 524 list.Pivots = make([]ListPivot, 0)
514 525 rows, err := db.Query(`SELECT
... ... @@ -535,7 +546,7 @@ func (list *ListConfig) SetPivot(db *sql.DB, objType string) error {
535 546 return nil
536 547 }
537 548  
538   -// getListDetails returns list details for the provided object type.
  549 +// SetDetails ...
539 550 func (list *ListConfig) SetDetails(db *sql.DB, objType string) error {
540 551 var resp ListDetails
541 552 rows, err := db.Query(`SELECT
... ... @@ -563,7 +574,7 @@ func (list *ListConfig) SetDetails(db *sql.DB, objType string) error {
563 574 return nil
564 575 }
565 576  
566   -// getListLiveGraph returns live graph for the provided object type.
  577 +// SetLiveGraph ...
567 578 func (list *ListConfig) SetLiveGraph(db *sql.DB, objType string) error {
568 579 var resp ListLiveGraph
569 580 rows, err := db.Query(`SELECT
... ...
... ... @@ -11,6 +11,7 @@ import (
11 11 "sync"
12 12 )
13 13  
  14 +// Dictionary ...
14 15 type Dictionary struct {
15 16 my sync.Mutex
16 17 locales map[string]map[string]string
... ... @@ -18,12 +19,14 @@ type Dictionary struct {
18 19 defaultLocale string
19 20 }
20 21  
  22 +// NewDictionary ...
21 23 func NewDictionary() *Dictionary {
22 24 return &Dictionary{
23 25 locales: map[string]map[string]string{},
24 26 }
25 27 }
26 28  
  29 +// AddTranslations ...
27 30 func (d *Dictionary) AddTranslations(directory string) error {
28 31 files, err := ioutil.ReadDir(directory)
29 32 if err != nil {
... ... @@ -64,14 +67,15 @@ func (d *Dictionary) AddTranslations(directory string) error {
64 67 return nil
65 68 }
66 69  
  70 +// GetBestMatchLocale ...
67 71 func (d *Dictionary) GetBestMatchLocale(req *http.Request) (best string) {
68 72 accepted := d.parseAcceptedLanguages(req.Header.Get("Accept-Language"))
69 73  
70   - for i, _ := range accepted {
  74 + for i := range accepted {
71 75 if accepted[i].Code == "*" {
72 76 return d.defaultLocale
73 77 }
74   - for j, _ := range d.supported {
  78 + for j := range d.supported {
75 79 if accepted[i].Code == d.supported[j] {
76 80 return d.supported[j]
77 81 }
... ... @@ -81,10 +85,12 @@ func (d *Dictionary) GetBestMatchLocale(req *http.Request) (best string) {
81 85 return d.defaultLocale
82 86 }
83 87  
  88 +// Translate ...
84 89 func (d *Dictionary) Translate(loc, key string) string {
85 90 return d.locales[loc][key]
86 91 }
87 92  
  93 +// SetDefaultLocale ...
88 94 func (d *Dictionary) SetDefaultLocale(loc string) error {
89 95 if !d.contains(loc) {
90 96 return fmt.Errorf("locale file not loaded: %s", loc)
... ... @@ -104,6 +110,7 @@ func (d *Dictionary) contains(loc string) bool {
104 110 return false
105 111 }
106 112  
  113 +// LangWeight ...
107 114 type LangWeight struct {
108 115 Code string
109 116 Weight float64
... ... @@ -115,13 +122,13 @@ func (d *Dictionary) parseAcceptedLanguages(accepted string) (langs []LangWeight
115 122 return langs
116 123 }
117 124  
  125 + var code string
  126 + var weight float64
  127 +
118 128 parts := strings.Split(accepted, ",")
119   - for i, _ := range parts {
  129 + for i := range parts {
120 130 parts[i] = strings.Trim(parts[i], " ")
121 131  
122   - var code string = ""
123   - var weight float64 = 0.0
124   -
125 132 cw := strings.Split(parts[i], ";")
126 133 paramCount := len(cw)
127 134  
... ...
... ... @@ -9,6 +9,7 @@ import (
9 9  
10 10 var httpLogger *gologger.Logger
11 11  
  12 +// SetHeaders ...
12 13 func SetHeaders(h http.HandlerFunc) http.HandlerFunc {
13 14 return func(w http.ResponseWriter, req *http.Request) {
14 15 SetDefaultHeaders(w)
... ... @@ -19,6 +20,7 @@ func SetHeaders(h http.HandlerFunc) http.HandlerFunc {
19 20 }
20 21 }
21 22  
  23 +// ParseForm ...
22 24 func ParseForm(h http.HandlerFunc) http.HandlerFunc {
23 25 return func(w http.ResponseWriter, req *http.Request) {
24 26 err := req.ParseForm()
... ... @@ -30,6 +32,7 @@ func ParseForm(h http.HandlerFunc) http.HandlerFunc {
30 32 }
31 33 }
32 34  
  35 +// ParseMultipartForm ...
33 36 func ParseMultipartForm(h http.HandlerFunc) http.HandlerFunc {
34 37 return func(w http.ResponseWriter, req *http.Request) {
35 38 err := req.ParseMultipartForm(32 << 20)
... ... @@ -41,11 +44,13 @@ func ParseMultipartForm(h http.HandlerFunc) http.HandlerFunc {
41 44 }
42 45 }
43 46  
  47 +// EnableLogging ...
44 48 func EnableLogging(log string) (err error) {
45 49 httpLogger, err = gologger.New(log, gologger.MaxLogSize5MB)
46 50 return err
47 51 }
48 52  
  53 +// Log ...
49 54 func Log(h http.HandlerFunc) http.HandlerFunc {
50 55 return func(w http.ResponseWriter, req *http.Request) {
51 56 t1 := time.Now()
... ... @@ -64,6 +69,7 @@ func Log(h http.HandlerFunc) http.HandlerFunc {
64 69 }
65 70 }
66 71  
  72 +// Auth ...
67 73 func Auth(roles string, h http.HandlerFunc) http.HandlerFunc {
68 74 return func(w http.ResponseWriter, req *http.Request) {
69 75 if _, err := AuthCheck(req, roles); err != nil {
... ... @@ -73,3 +79,4 @@ func Auth(roles string, h http.HandlerFunc) http.HandlerFunc {
73 79 h(w, req)
74 80 }
75 81 }
  82 +
... ...
... ... @@ -29,8 +29,10 @@ var (
29 29 logger *gologger.Logger
30 30 )
31 31  
  32 +// LangMap ...
32 33 type LangMap map[string]map[string]string
33 34  
  35 +// Field ...
34 36 type Field struct {
35 37 Parameter string `json:"param"`
36 38 Type string `json:"type"`
... ... @@ -38,18 +40,20 @@ type Field struct {
38 40 Editable bool `json:"editable"`
39 41 }
40 42  
  43 +// CorrelationField ...
41 44 type CorrelationField struct {
42 45 Result string `json:"result"`
43 46 Elements []string `json:"elements"`
44 47 Type string `json:"type"`
45 48 }
46 49  
  50 +// Translation ...
47 51 type Translation struct {
48 52 Language string `json:"language"`
49 53 FieldsLabels map[string]string `json:"fieldsLabels"`
50 54 }
51 55  
52   -// output
  56 +// PaginationLinks ...
53 57 type PaginationLinks struct {
54 58 Base string `json:"base"`
55 59 Next string `json:"next"`
... ... @@ -57,7 +61,7 @@ type PaginationLinks struct {
57 61 Self string `json:"self"`
58 62 }
59 63  
60   -// input
  64 +// PaginationParameters ...
61 65 type PaginationParameters struct {
62 66 URL string `json:"-"`
63 67 Offset int64 `json:"offset"`
... ... @@ -66,6 +70,7 @@ type PaginationParameters struct {
66 70 Order string `json:"order"`
67 71 }
68 72  
  73 +// GetPaginationParameters ...
69 74 // TODO(marko)
70 75 func GetPaginationParameters(req *http.Request) (p PaginationParameters) {
71 76 return p
... ... @@ -76,13 +81,14 @@ func (p *PaginationParameters) paginationLinks() (links PaginationLinks) {
76 81 return links
77 82 }
78 83  
  84 +// Payload ...
79 85 type Payload struct {
80 86 Method string `json:"method"`
81 87 Params map[string]string `json:"params"`
82 88 Lang []Translation `json:"lang"`
83 89 Fields []Field `json:"fields"`
84 90 Correlations []CorrelationField `json:"correlationFields"`
85   - IdField string `json:"idField"`
  91 + IDField string `json:"idField"`
86 92  
87 93 // Pagination
88 94 Count int64 `json:"count"`
... ... @@ -101,10 +107,12 @@ func (p *Payload) addLang(code string, labels map[string]string) {
101 107 p.Lang = append(p.Lang, t)
102 108 }
103 109  
  110 +// SetData ...
104 111 func (p *Payload) SetData(data interface{}) {
105 112 p.Data = data
106 113 }
107 114  
  115 +// SetPaginationInfo ...
108 116 func (p *Payload) SetPaginationInfo(count, total int64, params PaginationParameters) {
109 117 p.Count = count
110 118 p.Total = total
... ... @@ -152,32 +160,37 @@ func InitPayloadsMetadata(drv string, db *sql.DB, project string) error {
152 160 return nil
153 161 }
154 162  
  163 +// EnableHotloading ...
155 164 func EnableHotloading(interval int) {
156 165 if interval > 0 {
157 166 go hotload(interval)
158 167 }
159 168 }
160 169  
  170 +// GetMetadataForAllEntities ...
161 171 func GetMetadataForAllEntities() map[string]Payload {
162 172 return metadata
163 173 }
164 174  
  175 +// GetMetadataForEntity ...
165 176 func GetMetadataForEntity(t string) (Payload, bool) {
166 177 p, ok := metadata[t]
167 178 return p, ok
168 179 }
169 180  
  181 +// QueEntityModelUpdate ...
170 182 func QueEntityModelUpdate(entityType string, v interface{}) {
171 183 updateQue[entityType], _ = json.Marshal(v)
172 184 }
173 185  
  186 +// UpdateEntityModels ...
174 187 func UpdateEntityModels(command string) (total, upd, add int, err error) {
175 188 if command != "force" && command != "missing" {
176 189 return total, 0, 0, errors.New("webutility: unknown command: " + command)
177 190 }
178 191  
179 192 if !inited {
180   - return 0, 0, 0, errors.New("webutility: metadata not initialized but update was tried.")
  193 + return 0, 0, 0, errors.New("webutility: metadata not initialized but update was tried")
181 194 }
182 195  
183 196 total = len(updateQue)
... ... @@ -185,7 +198,7 @@ func UpdateEntityModels(command string) (total, upd, add int, err error) {
185 198 toUpdate := make([]string, 0)
186 199 toAdd := make([]string, 0)
187 200  
188   - for k, _ := range updateQue {
  201 + for k := range updateQue {
189 202 if _, exists := metadata[k]; exists {
190 203 if command == "force" {
191 204 toUpdate = append(toUpdate, k)
... ... @@ -277,15 +290,7 @@ func initMetadata(project string) error {
277 290 return nil
278 291 }
279 292  
280   -// TODO(marko):
281   -//
282   -// Currently supports only one hardcoded language...
283   -//
284   -//
285   -//
286   -//
287   -//
288   -// Metadata file ecpected format:
  293 +// LoadMetadataFromFile expects file in format:
289 294 //
290 295 // [ payload A identifier ]
291 296 // key1 : value1
... ... @@ -295,6 +300,8 @@ func initMetadata(project string) error {
295 300 // key1 : value1
296 301 // key2 : value2
297 302 // ...
  303 +//
  304 +// TODO(marko): Currently supports only one hardcoded language...
298 305 func LoadMetadataFromFile(path string) error {
299 306 lines, err := ReadFileLines(path)
300 307 if err != nil {
... ... @@ -319,12 +326,12 @@ func LoadMetadataFromFile(path string) error {
319 326 }
320 327  
321 328 if name == "" {
322   - return fmt.Errorf("webutility: LoadMetadataFromFile: error on line %d: [no header] [%s]\n", i+1, l)
  329 + return fmt.Errorf("webutility: LoadMetadataFromFile: error on line %d: [no header] [%s]", i+1, l)
323 330 }
324 331  
325 332 parts := strings.Split(l, ":")
326 333 if len(parts) != 2 {
327   - return fmt.Errorf("webutility: LoadMetadataFromFile: error on line %d: [invalid format] [%s]\n", i+1, l)
  334 + return fmt.Errorf("webutility: LoadMetadataFromFile: error on line %d: [invalid format] [%s]", i+1, l)
328 335 }
329 336  
330 337 k := trimSpaces(parts[0])
... ... @@ -345,6 +352,7 @@ func trimSpaces(s string) string {
345 352 return strings.TrimSpace(s)
346 353 }
347 354  
  355 +// ReadFileLines ...
348 356 // TODO(marko): Move to separate package
349 357 func ReadFileLines(path string) ([]string, error) {
350 358 f, err := os.Open(path)
... ...
... ... @@ -2,11 +2,12 @@ package webutility
2 2  
3 3 import "database/sql"
4 4  
  5 +// SelectConfig ...
5 6 type SelectConfig struct {
6 7 ListObjType string `json:"listObjectType"`
7 8 ObjType string `json:"objectType"`
8 9 Type string `json:"type"`
9   - IdField string `json:"idField"`
  10 + IDField string `json:"idField"`
10 11 LabelField string `json:"labelField"`
11 12 ValueField string `json:"valueField"`
12 13 }
... ... @@ -32,7 +33,7 @@ func GetSelectConfig(db *sql.DB, otype string) ([]SelectConfig, error) {
32 33  
33 34 var sc SelectConfig
34 35 for rows.Next() {
35   - rows.Scan(&sc.ListObjType, &sc.ObjType, &sc.IdField, &sc.LabelField, &sc.Type, &sc.ValueField)
  36 + rows.Scan(&sc.ListObjType, &sc.ObjType, &sc.IDField, &sc.LabelField, &sc.Type, &sc.ValueField)
36 37 resp = append(resp, sc)
37 38 }
38 39 if rows.Err() != nil {
... ...
string_sanitisation.go
... ... @@ -2,9 +2,9 @@ package webutility
2 2  
3 3 import "strings"
4 4  
5   -var patern string = "\"';&*<>=\`:"
  5 +const patern = "\"';&*<>=\`:"
6 6  
7   -// SQLSafeString removes characters from s found in patern and returns new modified string.
  7 +// SanitiseString removes characters from s found in patern and returns new modified string.
8 8 func SanitiseString(s string) (safe string) {
9 9 for _, c := range patern {
10 10 safe = strings.Replace(s, string(c), "", -1)
... ...