diff --git a/auth.go b/auth.go index 64ca043..5ce6ce9 100644 --- a/auth.go +++ b/auth.go @@ -29,6 +29,7 @@ type TokenClaims struct { ExpiresIn int64 `json:"expires_in"` } +// InitJWT ... func InitJWT(issuer, secret string) { _issuer = issuer _secret = secret @@ -130,6 +131,7 @@ func RefreshAuthToken(tok string) (TokenClaims, error) { return CreateAuthToken(claims.Username, claims.RoleName, claims.RoleID) } +// AuthCheck ... func AuthCheck(req *http.Request, roles string) (*TokenClaims, error) { // validate token and check expiration date claims, err := GetTokenClaims(req) @@ -151,7 +153,7 @@ func AuthCheck(req *http.Request, roles string) (*TokenClaims, error) { } parts := strings.Split(roles, ",") - for i, _ := range parts { + for i := range parts { r := strings.Trim(parts[i], " ") if claims.RoleName == r { return claims, nil diff --git a/default_values.go b/default_values.go index 36ae0bb..f74c6cc 100644 --- a/default_values.go +++ b/default_values.go @@ -1,5 +1,6 @@ package webutility +// Int32ValueOrDefault ... func Int32ValueOrDefault(val *interface{}) (def int32) { if *val != nil { def = (*val).(int32) @@ -7,6 +8,7 @@ func Int32ValueOrDefault(val *interface{}) (def int32) { return def } +// Int64ValueOrDefault ... func Int64ValueOrDefault(val *interface{}) (def int64) { if *val != nil { def = (*val).(int64) @@ -14,6 +16,7 @@ func Int64ValueOrDefault(val *interface{}) (def int64) { return def } +// Uint32ValueOrDefault ... func Uint32ValueOrDefault(val *interface{}) (def uint32) { if *val != nil { def = (*val).(uint32) @@ -21,6 +24,7 @@ func Uint32ValueOrDefault(val *interface{}) (def uint32) { return def } +// Uint64ValueOrDefault ... func Uint64ValueOrDefault(val *interface{}) (def uint64) { if *val != nil { def = (*val).(uint64) @@ -28,6 +32,7 @@ func Uint64ValueOrDefault(val *interface{}) (def uint64) { return def } +// Float32ValueOrDefault ... func Float32ValueOrDefault(val *interface{}) (def float32) { if *val != nil { def = (*val).(float32) @@ -35,6 +40,7 @@ func Float32ValueOrDefault(val *interface{}) (def float32) { return def } +// Float64ValueOrDefault ... func Float64ValueOrDefault(val *interface{}) (def float64) { if *val != nil { return (*val).(float64) @@ -42,9 +48,11 @@ func Float64ValueOrDefault(val *interface{}) (def float64) { return def } +// StringValueOrDefault ... func StringValueOrDefault(val *interface{}) (def string) { if *val != nil { def = (*val).(string) } return def } + diff --git a/email.go b/email.go index 3ff4d7b..718708c 100644 --- a/email.go +++ b/email.go @@ -10,76 +10,100 @@ import ( "strings" ) +// Email ... type Email struct { - To []string - From string - Subject string - Body string + recipients []string + sender string + subject string + body string config *EmailConfig } +// NewEmail ... func NewEmail() *Email { - return &Email{ - To: nil, - From: "", - Subject: "", - Body: "", - config: nil, + return new(Email) +} + +// EmailConfig ... +type EmailConfig struct { + ServerName string `json:"-"` + Identity string `json:"-"` + Username string `json:"username"` + Password string `json:"password"` + Host string `json:"host"` + Port int `json:"port"` +} + +// NewEmailConfig ... +func NewEmailConfig(ident, uname, pword, host string, port int) *EmailConfig { + return &EmailConfig{ + ServerName: host + fmt.Sprintf(":%d", port), + Identity: ident, + Username: uname, + Password: pword, + Host: host, + Port: port, } } +// Config ... func (e *Email) Config(cfg *EmailConfig) { e.config = cfg } -func (e *Email) SetFrom(from string) { - e.From = from +// Sender ... +func (e *Email) Sender(from string) { + e.sender = from } -func (e *Email) SetTo(to []string) { - e.To = to +// AddRecipient ... +func (e *Email) AddRecipient(r string) { + e.recipients = append(e.recipients, r) } -func (e *Email) SetSubject(sub string) { - e.Subject = sub +// Subject ... +func (e *Email) Subject(sub string) { + e.subject = sub } -func (e *Email) SetBody(body string) { - e.Body = body +func (e *Email) Write(body string) { + e.body = body } func (e *Email) String() string { var str strings.Builder - str.WriteString("From:" + e.From + "\r\n") + str.WriteString("From:" + e.sender + "\r\n") str.WriteString("To:") - for i, _ := range e.To { + for i := range e.recipients { if i > 0 { str.WriteString(",") } - str.WriteString(e.To[i]) + str.WriteString(e.recipients[i]) } str.WriteString("\r\n") - str.WriteString("Subject:" + e.Subject + "\r\n") + str.WriteString("Subject:" + e.subject + "\r\n") // body - str.WriteString("\r\n" + e.Body + "\r\n") + str.WriteString("\r\n" + e.body + "\r\n") return str.String() } +// Bytes ... func (e *Email) Bytes() []byte { return []byte(e.String()) } -func (email *Email) Send() error { - if email.config == nil { +// Send ... +func (e *Email) Send() error { + if e.config == nil { return errors.New("email configuration not provided") } - conf := email.config + conf := e.config c, err := smtp.Dial(conf.ServerName) if err != nil { @@ -87,10 +111,12 @@ func (email *Email) Send() error { } defer c.Close() - // not sure if this is needed - //if err = c.Hello(conf.ServerName); err != nil { - // return err - //} + /* + // not sure if this is needed + if err = c.Hello(conf.ServerName); err != nil { + return err + } + */ if ok, _ := c.Extension("STARTTLS"); ok { // disable stupid tls check for self-signed certificates @@ -98,10 +124,12 @@ func (email *Email) Send() error { ServerName: conf.ServerName, InsecureSkipVerify: true, } - // for golang testing - //if testHookStartTLS != nil { - // testHookStartTLS(config) - //} + /* + // for golang testing + if testHookStartTLS != nil { + testHookStartTLS(config) + } + */ if err = c.StartTLS(config); err != nil { return err } @@ -125,11 +153,11 @@ func (email *Email) Send() error { return err } - if err = c.Mail(email.From); err != nil { + if err = c.Mail(e.sender); err != nil { return err } - for _, addr := range email.To { + for _, addr := range e.recipients { if err = c.Rcpt(addr); err != nil { return err } @@ -140,7 +168,7 @@ func (email *Email) Send() error { return err } - _, err = w.Write(email.Bytes()) + _, err = w.Write(e.Bytes()) if err != nil { return err } @@ -152,23 +180,3 @@ func (email *Email) Send() error { return c.Quit() } - -type EmailConfig struct { - ServerName string `json:"-"` - Identity string `json:"-"` - Username string `json:"username"` - Password string `json:"password"` - Host string `json:"host"` - Port int `json:"port"` -} - -func NewEmailConfig(ident, uname, pword, host string, port int) *EmailConfig { - return &EmailConfig{ - ServerName: host + fmt.Sprintf(":%d", port), - Identity: ident, - Username: uname, - Password: pword, - Host: host, - Port: port, - } -} diff --git a/filtering.go b/filtering.go index 82db975..2fe650d 100644 --- a/filtering.go +++ b/filtering.go @@ -7,21 +7,26 @@ import ( "strings" ) +// Filter ... type Filter map[string][]string +// Get ... func (f Filter) Get(key string) (values []string, ok bool) { values, ok = f[key] return values, ok } +// Count ... func (f Filter) Count() int { return len(f) } +// Add ... func (f Filter) Add(key, val string) { f[key] = append(f[key], val) } +// ValueAt ... func (f Filter) ValueAt(val string, index int) string { if filter, ok := f[val]; ok { if len(filter) > index { @@ -32,15 +37,15 @@ func (f Filter) ValueAt(val string, index int) string { return "" } -func (fs Filter) validate(validFilters []string) (Filter, bool) { +func (f Filter) validate(validFilters []string) (Filter, bool) { goodFilters := make(Filter) cnt, len := 0, 0 - for f, _ := range fs { + for fi := range f { len++ for _, v := range validFilters { - if f == v { + if fi == v { cnt++ - goodFilters[f] = fs[f] + goodFilters[fi] = f[fi] } } } @@ -54,14 +59,14 @@ func (fs Filter) validate(validFilters []string) (Filter, bool) { return goodFilters, result } -// requires input in format: "param1::value1|param2::value2..." +// ParseFilters requires input in format: "param1::value1|param2::value2..." func ParseFilters(req *http.Request, header string) (filters Filter) { q := req.FormValue(header) q = strings.Trim(q, "\"") kvp := strings.Split(q, "|") filters = make(Filter, len(kvp)) - for i, _ := range kvp { + for i := range kvp { kv := strings.Split(kvp[i], "::") if len(kv) == 2 { key, _ := url.QueryUnescape(kv[0]) @@ -78,7 +83,8 @@ func ParseFilters(req *http.Request, header string) (filters Filter) { return filters } -// TODO(marko): very dodgy, needs more robustness +// MakeFilterString is very dodgy, needs more robustness. +// TODO(marko) func MakeFilterString(prefix string, filters Filter, validFilters []string) (res string, ok bool) { if prefix != "" { prefix += "." diff --git a/format.go b/format.go index b40dbf3..755b97f 100644 --- a/format.go +++ b/format.go @@ -33,6 +33,7 @@ func EqualQuotes(stmt string) string { return stmt } +// EqualString ... func EqualString(stmt string) string { if stmt != "" { stmt = fmt.Sprintf(" = %s", stmt) @@ -48,3 +49,4 @@ func LikeQuotes(stmt string) string { } return stmt } + diff --git a/http.go b/http.go index 932de59..fd425c5 100644 --- a/http.go +++ b/http.go @@ -6,12 +6,14 @@ import ( "net/http" ) +// StatusRecorder ... type StatusRecorder struct { writer http.ResponseWriter status int size int } +// NewStatusRecorder ... func NewStatusRecorder(w http.ResponseWriter) *StatusRecorder { return &StatusRecorder{ writer: w, @@ -20,27 +22,29 @@ func NewStatusRecorder(w http.ResponseWriter) *StatusRecorder { } } -// http.ResponseWriter interface +// WriteHeader is a wrapper http.ResponseWriter interface func (r *StatusRecorder) WriteHeader(code int) { r.status = code r.writer.WriteHeader(code) } -// http.ResponseWriter interface +// Write is a wrapper for http.ResponseWriter interface func (r *StatusRecorder) Write(in []byte) (int, error) { r.size = len(in) return r.writer.Write(in) } -// http.ResponseWriter interface +// Header is a wrapper for http.ResponseWriter interface func (r *StatusRecorder) Header() http.Header { return r.writer.Header() } +// Status ... func (r *StatusRecorder) Status() int { return r.status } +// Size ... func (r *StatusRecorder) Size() int { return r.size } @@ -62,6 +66,7 @@ func SetDefaultHeaders(w http.ResponseWriter) { w.Header().Set("Content-Type", "application/json; charset=utf-8") } +// GetLocale ... func GetLocale(req *http.Request, dflt string) string { loc := req.FormValue("locale") if loc == "" { @@ -70,7 +75,7 @@ func GetLocale(req *http.Request, dflt string) string { return loc } -// 2xx +// Success ... func Success(w http.ResponseWriter, payload interface{}, code int) { w.WriteHeader(code) if payload != nil { @@ -78,12 +83,12 @@ func Success(w http.ResponseWriter, payload interface{}, code int) { } } -// 200 +// OK ... func OK(w http.ResponseWriter, payload interface{}) { Success(w, payload, http.StatusOK) } -// 201 +// Created ... func Created(w http.ResponseWriter, payload interface{}) { Success(w, payload, http.StatusCreated) } @@ -93,39 +98,40 @@ type weberror struct { Error string `json:"error"` } -// 4xx; 5xx +// Error ... func Error(w http.ResponseWriter, r *http.Request, code int, err string) { werr := weberror{Error: err, Request: r.Method + " " + r.RequestURI} w.WriteHeader(code) json.NewEncoder(w).Encode(werr) } -// 400 +// BadRequest ... func BadRequest(w http.ResponseWriter, r *http.Request, err string) { Error(w, r, http.StatusBadRequest, err) } -// 401 +// Unauthorized ... func Unauthorized(w http.ResponseWriter, r *http.Request, err string) { Error(w, r, http.StatusUnauthorized, err) } -// 403 +// Forbidden ... func Forbidden(w http.ResponseWriter, r *http.Request, err string) { Error(w, r, http.StatusForbidden, err) } -// 404 +// NotFound ... func NotFound(w http.ResponseWriter, r *http.Request, err string) { Error(w, r, http.StatusNotFound, err) } -// 409 +// Conflict ... func Conflict(w http.ResponseWriter, r *http.Request, err string) { Error(w, r, http.StatusConflict, err) } -// 500 +// InternalServerError ... func InternalServerError(w http.ResponseWriter, r *http.Request, err string) { Error(w, r, http.StatusInternalServerError, err) } + diff --git a/list_config.go b/list_config.go index f4fe809..0227115 100644 --- a/list_config.go +++ b/list_config.go @@ -5,6 +5,7 @@ import ( "fmt" ) +// ListOptions ... type ListOptions struct { GlobalFilter bool `json:"globalFilter"` LocalFilters bool `json:"localFilters"` @@ -16,6 +17,7 @@ type ListOptions struct { Total bool `json:"total"` } +// ListFilter ... type ListFilter struct { Position uint32 `json:"-"` ObjectType string `json:"-"` @@ -26,6 +28,7 @@ type ListFilter struct { DropdownConfig Dropdown `json:"dropdownConfig"` } +// Dropdown ... type Dropdown struct { ObjectType string `json:"objectType"` FiltersField string `json:"filtersField"` @@ -33,6 +36,7 @@ type Dropdown struct { LabelField string `json:"labelField"` } +// ListGraph ... type ListGraph struct { ObjectType string `json:"objectType"` X string `json:"xField"` @@ -41,6 +45,7 @@ type ListGraph struct { Label string `json:"label"` } +// ListActions ... type ListActions struct { Create bool `json:"create"` Update bool `json:"update"` @@ -53,6 +58,7 @@ type ListActions struct { ShowFile bool `json:"showFile"` } +// ListNavNode ... type ListNavNode struct { ObjectType string `json:"objectType"` LabelField string `json:"label"` @@ -62,12 +68,14 @@ type ListNavNode struct { ParentFilterField string `json:"parentFilterField"` } +// ListParentNode ... type ListParentNode struct { ObjectType string `json:"objectType"` LabelField string `json:"labelField"` FilterField string `json:"filterField"` } +// ListPivot ... type ListPivot struct { ObjectType string `json:"objectType"` GroupField string `json:"groupField"` @@ -75,6 +83,7 @@ type ListPivot struct { Value string `json:"valueField"` } +// ListDetails ... type ListDetails struct { ObjectType string `json:"objectType"` ParentObjectType string `json:"parentObjectType"` @@ -82,12 +91,14 @@ type ListDetails struct { SingleDetail bool `json:"singleDetail"` } +// ListLiveGraph ... type ListLiveGraph struct { ObjectType string `json:"objectType"` ValueFields string `json:"valueFields"` LabelFields string `json:"labelFields"` } +// ListConfig ... type ListConfig struct { ObjectType string `json:"objectType"` Title string `json:"title"` @@ -152,7 +163,7 @@ func GetListConfigObjectIDField(db *sql.DB, otype string) string { return resp } -// newDefaultList returns default configuration for the provided object type. +// NewListConfig returns default configuration for the provided object type. func NewListConfig(objType string) ListConfig { list := ListConfig{ ObjectType: objType, @@ -182,7 +193,7 @@ func NewListConfig(objType string) ListConfig { return list } -// setListParams sets the default parameters of the provided configuration list for the provided object type. +// setParams sets the default parameters of the provided configuration list for the provided object type. func (list *ListConfig) setParams(db *sql.DB, objType string) error { rows, err := db.Query(`SELECT OBJECT_TYPE, @@ -215,7 +226,7 @@ func (list *ListConfig) setParams(db *sql.DB, objType string) error { return nil } -// ListNavigation returns list navigation node slice for the provided objectType. +// SetNavigation returns set's navigation nodes for listObjType object type. func (list *ListConfig) SetNavigation(db *sql.DB, listObjType string) error { list.Navigation = make([]ListNavNode, 0) rows, err := db.Query(`SELECT @@ -247,7 +258,7 @@ func (list *ListConfig) SetNavigation(db *sql.DB, listObjType string) error { return nil } -// getListActions returns list actions for the provided object type. +// SetActions sets list's actions based for objType object type. func (list *ListConfig) SetActions(db *sql.DB, objType string) error { rows, err := db.Query(`SELECT ACTION_CREATE, @@ -286,7 +297,7 @@ func (list *ListConfig) SetActions(db *sql.DB, objType string) error { return nil } -// getListFiters returns list filter slice for the provided object type. +// SetFilters ... func (list *ListConfig) SetFilters(db *sql.DB, objType string) error { list.Filters = make([]ListFilter, 0) filtersFields, err := list.GetFilterFieldsAndPosition(db, objType) @@ -294,7 +305,7 @@ func (list *ListConfig) SetFilters(db *sql.DB, objType string) error { return err } for field, pos := range filtersFields { - filters, _ := list.GetFiltersByFilterField(db, field) + filters, _ := list.getFiltersByFilterField(db, field) for _, filter := range filters { var f ListFilter f.Position = pos @@ -318,7 +329,7 @@ func (list *ListConfig) SetFilters(db *sql.DB, objType string) error { return nil } -// getFilterFieldsAndPosition returns a map of filter fields and their respective position in the menu. +// GetFilterFieldsAndPosition returns a map of filter fields and their respective position in the menu. func (list *ListConfig) GetFilterFieldsAndPosition(db *sql.DB, objType string) (map[string]uint32, error) { filtersField := make(map[string]uint32, 0) rows, err := db.Query(`SELECT @@ -349,8 +360,8 @@ type _filter struct { Type string } -// getFiltersByFilterField returns filter slice for the provided filter field. -func (list *ListConfig) GetFiltersByFilterField(db *sql.DB, filtersField string) ([]_filter, error) { +// getFiltersByFilterField ... +func (list *ListConfig) getFiltersByFilterField(db *sql.DB, filtersField string) ([]_filter, error) { resp := make([]_filter, 0) rows, err := db.Query(`SELECT FILTERS_TYPE, @@ -374,7 +385,7 @@ func (list *ListConfig) GetFiltersByFilterField(db *sql.DB, filtersField string) return resp, nil } -// getFilterDropdownConfig returns dropdown menu for the provided filter field. +// SetDropdownConfig ... func (f *ListFilter) SetDropdownConfig(db *sql.DB, filtersField string) error { var resp Dropdown rows, err := db.Query(`SELECT @@ -417,7 +428,7 @@ func (list *ListConfig) sortFilters() { } } -// getListGraph return list graph slice for the provided object type. +// SetGraph ... func (list *ListConfig) SetGraph(db *sql.DB, objType string) error { list.Graphs = make([]ListGraph, 0) rows, err := db.Query(`SELECT @@ -445,7 +456,7 @@ func (list *ListConfig) SetGraph(db *sql.DB, objType string) error { return nil } -// getListOptions returns list options for the provided object type. +// SetOptions ... func (list *ListConfig) SetOptions(db *sql.DB, objType string) error { rows, err := db.Query(`SELECT GLOBAL_FILTER, @@ -482,7 +493,7 @@ func (list *ListConfig) SetOptions(db *sql.DB, objType string) error { return nil } -// getListParent returns list parent node slice for the provided object type. +// SetParent ... func (list *ListConfig) SetParent(db *sql.DB, objType string) error { list.Parent = make([]ListParentNode, 0) rows, err := db.Query(`SELECT @@ -508,7 +519,7 @@ func (list *ListConfig) SetParent(db *sql.DB, objType string) error { return nil } -// getListPivot list pivot slice for the provided object type. +// SetPivot ... func (list *ListConfig) SetPivot(db *sql.DB, objType string) error { list.Pivots = make([]ListPivot, 0) rows, err := db.Query(`SELECT @@ -535,7 +546,7 @@ func (list *ListConfig) SetPivot(db *sql.DB, objType string) error { return nil } -// getListDetails returns list details for the provided object type. +// SetDetails ... func (list *ListConfig) SetDetails(db *sql.DB, objType string) error { var resp ListDetails rows, err := db.Query(`SELECT @@ -563,7 +574,7 @@ func (list *ListConfig) SetDetails(db *sql.DB, objType string) error { return nil } -// getListLiveGraph returns live graph for the provided object type. +// SetLiveGraph ... func (list *ListConfig) SetLiveGraph(db *sql.DB, objType string) error { var resp ListLiveGraph rows, err := db.Query(`SELECT diff --git a/localization.go b/localization.go index aa4bdb1..be063d4 100644 --- a/localization.go +++ b/localization.go @@ -11,6 +11,7 @@ import ( "sync" ) +// Dictionary ... type Dictionary struct { my sync.Mutex locales map[string]map[string]string @@ -18,12 +19,14 @@ type Dictionary struct { defaultLocale string } +// NewDictionary ... func NewDictionary() *Dictionary { return &Dictionary{ locales: map[string]map[string]string{}, } } +// AddTranslations ... func (d *Dictionary) AddTranslations(directory string) error { files, err := ioutil.ReadDir(directory) if err != nil { @@ -64,14 +67,15 @@ func (d *Dictionary) AddTranslations(directory string) error { return nil } +// GetBestMatchLocale ... func (d *Dictionary) GetBestMatchLocale(req *http.Request) (best string) { accepted := d.parseAcceptedLanguages(req.Header.Get("Accept-Language")) - for i, _ := range accepted { + for i := range accepted { if accepted[i].Code == "*" { return d.defaultLocale } - for j, _ := range d.supported { + for j := range d.supported { if accepted[i].Code == d.supported[j] { return d.supported[j] } @@ -81,10 +85,12 @@ func (d *Dictionary) GetBestMatchLocale(req *http.Request) (best string) { return d.defaultLocale } +// Translate ... func (d *Dictionary) Translate(loc, key string) string { return d.locales[loc][key] } +// SetDefaultLocale ... func (d *Dictionary) SetDefaultLocale(loc string) error { if !d.contains(loc) { return fmt.Errorf("locale file not loaded: %s", loc) @@ -104,6 +110,7 @@ func (d *Dictionary) contains(loc string) bool { return false } +// LangWeight ... type LangWeight struct { Code string Weight float64 @@ -115,13 +122,13 @@ func (d *Dictionary) parseAcceptedLanguages(accepted string) (langs []LangWeight return langs } + var code string + var weight float64 + parts := strings.Split(accepted, ",") - for i, _ := range parts { + for i := range parts { parts[i] = strings.Trim(parts[i], " ") - var code string = "" - var weight float64 = 0.0 - cw := strings.Split(parts[i], ";") paramCount := len(cw) diff --git a/middleware.go b/middleware.go index f0a6d9c..4fb5175 100644 --- a/middleware.go +++ b/middleware.go @@ -9,6 +9,7 @@ import ( var httpLogger *gologger.Logger +// SetHeaders ... func SetHeaders(h http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { SetDefaultHeaders(w) @@ -19,6 +20,7 @@ func SetHeaders(h http.HandlerFunc) http.HandlerFunc { } } +// ParseForm ... func ParseForm(h http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { err := req.ParseForm() @@ -30,6 +32,7 @@ func ParseForm(h http.HandlerFunc) http.HandlerFunc { } } +// ParseMultipartForm ... func ParseMultipartForm(h http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { err := req.ParseMultipartForm(32 << 20) @@ -41,11 +44,13 @@ func ParseMultipartForm(h http.HandlerFunc) http.HandlerFunc { } } +// EnableLogging ... func EnableLogging(log string) (err error) { httpLogger, err = gologger.New(log, gologger.MaxLogSize5MB) return err } +// Log ... func Log(h http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { t1 := time.Now() @@ -64,6 +69,7 @@ func Log(h http.HandlerFunc) http.HandlerFunc { } } +// Auth ... func Auth(roles string, h http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { if _, err := AuthCheck(req, roles); err != nil { @@ -73,3 +79,4 @@ func Auth(roles string, h http.HandlerFunc) http.HandlerFunc { h(w, req) } } + diff --git a/payload.go b/payload.go index 180c54a..9978586 100644 --- a/payload.go +++ b/payload.go @@ -29,8 +29,10 @@ var ( logger *gologger.Logger ) +// LangMap ... type LangMap map[string]map[string]string +// Field ... type Field struct { Parameter string `json:"param"` Type string `json:"type"` @@ -38,18 +40,20 @@ type Field struct { Editable bool `json:"editable"` } +// CorrelationField ... type CorrelationField struct { Result string `json:"result"` Elements []string `json:"elements"` Type string `json:"type"` } +// Translation ... type Translation struct { Language string `json:"language"` FieldsLabels map[string]string `json:"fieldsLabels"` } -// output +// PaginationLinks ... type PaginationLinks struct { Base string `json:"base"` Next string `json:"next"` @@ -57,7 +61,7 @@ type PaginationLinks struct { Self string `json:"self"` } -// input +// PaginationParameters ... type PaginationParameters struct { URL string `json:"-"` Offset int64 `json:"offset"` @@ -66,6 +70,7 @@ type PaginationParameters struct { Order string `json:"order"` } +// GetPaginationParameters ... // TODO(marko) func GetPaginationParameters(req *http.Request) (p PaginationParameters) { return p @@ -76,13 +81,14 @@ func (p *PaginationParameters) paginationLinks() (links PaginationLinks) { return links } +// Payload ... type Payload struct { Method string `json:"method"` Params map[string]string `json:"params"` Lang []Translation `json:"lang"` Fields []Field `json:"fields"` Correlations []CorrelationField `json:"correlationFields"` - IdField string `json:"idField"` + IDField string `json:"idField"` // Pagination Count int64 `json:"count"` @@ -101,10 +107,12 @@ func (p *Payload) addLang(code string, labels map[string]string) { p.Lang = append(p.Lang, t) } +// SetData ... func (p *Payload) SetData(data interface{}) { p.Data = data } +// SetPaginationInfo ... func (p *Payload) SetPaginationInfo(count, total int64, params PaginationParameters) { p.Count = count p.Total = total @@ -152,32 +160,37 @@ func InitPayloadsMetadata(drv string, db *sql.DB, project string) error { return nil } +// EnableHotloading ... func EnableHotloading(interval int) { if interval > 0 { go hotload(interval) } } +// GetMetadataForAllEntities ... func GetMetadataForAllEntities() map[string]Payload { return metadata } +// GetMetadataForEntity ... func GetMetadataForEntity(t string) (Payload, bool) { p, ok := metadata[t] return p, ok } +// QueEntityModelUpdate ... func QueEntityModelUpdate(entityType string, v interface{}) { updateQue[entityType], _ = json.Marshal(v) } +// UpdateEntityModels ... func UpdateEntityModels(command string) (total, upd, add int, err error) { if command != "force" && command != "missing" { return total, 0, 0, errors.New("webutility: unknown command: " + command) } if !inited { - return 0, 0, 0, errors.New("webutility: metadata not initialized but update was tried.") + return 0, 0, 0, errors.New("webutility: metadata not initialized but update was tried") } total = len(updateQue) @@ -185,7 +198,7 @@ func UpdateEntityModels(command string) (total, upd, add int, err error) { toUpdate := make([]string, 0) toAdd := make([]string, 0) - for k, _ := range updateQue { + for k := range updateQue { if _, exists := metadata[k]; exists { if command == "force" { toUpdate = append(toUpdate, k) @@ -277,15 +290,7 @@ func initMetadata(project string) error { return nil } -// TODO(marko): -// -// Currently supports only one hardcoded language... -// -// -// -// -// -// Metadata file ecpected format: +// LoadMetadataFromFile expects file in format: // // [ payload A identifier ] // key1 : value1 @@ -295,6 +300,8 @@ func initMetadata(project string) error { // key1 : value1 // key2 : value2 // ... +// +// TODO(marko): Currently supports only one hardcoded language... func LoadMetadataFromFile(path string) error { lines, err := ReadFileLines(path) if err != nil { @@ -319,12 +326,12 @@ func LoadMetadataFromFile(path string) error { } if name == "" { - return fmt.Errorf("webutility: LoadMetadataFromFile: error on line %d: [no header] [%s]\n", i+1, l) + return fmt.Errorf("webutility: LoadMetadataFromFile: error on line %d: [no header] [%s]", i+1, l) } parts := strings.Split(l, ":") if len(parts) != 2 { - return fmt.Errorf("webutility: LoadMetadataFromFile: error on line %d: [invalid format] [%s]\n", i+1, l) + return fmt.Errorf("webutility: LoadMetadataFromFile: error on line %d: [invalid format] [%s]", i+1, l) } k := trimSpaces(parts[0]) @@ -345,6 +352,7 @@ func trimSpaces(s string) string { return strings.TrimSpace(s) } +// ReadFileLines ... // TODO(marko): Move to separate package func ReadFileLines(path string) ([]string, error) { f, err := os.Open(path) diff --git a/select_config.go b/select_config.go index c89277b..dec56d9 100644 --- a/select_config.go +++ b/select_config.go @@ -2,11 +2,12 @@ package webutility import "database/sql" +// SelectConfig ... type SelectConfig struct { ListObjType string `json:"listObjectType"` ObjType string `json:"objectType"` Type string `json:"type"` - IdField string `json:"idField"` + IDField string `json:"idField"` LabelField string `json:"labelField"` ValueField string `json:"valueField"` } @@ -32,7 +33,7 @@ func GetSelectConfig(db *sql.DB, otype string) ([]SelectConfig, error) { var sc SelectConfig for rows.Next() { - rows.Scan(&sc.ListObjType, &sc.ObjType, &sc.IdField, &sc.LabelField, &sc.Type, &sc.ValueField) + rows.Scan(&sc.ListObjType, &sc.ObjType, &sc.IDField, &sc.LabelField, &sc.Type, &sc.ValueField) resp = append(resp, sc) } if rows.Err() != nil { diff --git a/string_sanitisation.go b/string_sanitisation.go index 8b81b3f..54c9bef 100644 --- a/string_sanitisation.go +++ b/string_sanitisation.go @@ -2,9 +2,9 @@ package webutility import "strings" -var patern string = "\"';&*<>=\\`:" +const patern = "\"';&*<>=\\`:" -// SQLSafeString removes characters from s found in patern and returns new modified string. +// SanitiseString removes characters from s found in patern and returns new modified string. func SanitiseString(s string) (safe string) { for _, c := range patern { safe = strings.Replace(s, string(c), "", -1)