Commit 25e0015504e59050a2b2e299e6bb89ad2522282f

Authored by Marko Tikvić
1 parent 90fd36e9b6
Exists in master and in 1 other branch v2

exported everything

format_utility.go
1 package restutility 1 package restutility
2 2
3 import ( 3 import (
4 "strings" 4 "strings"
5 "time" 5 "time"
6 "strconv" 6 "strconv"
7 ) 7 )
8 8
9 //// 9 func UnixToDate(input int64) time.Time {
10 //// TIME FORMAT UTILITY
11 ////
12
13 func unixToDate(input int64) time.Time {
14 return time.Unix(input, 0) 10 return time.Unix(input, 0)
15 } 11 }
16 12
17 func dateToUnix(input interface{}) int64 { 13 func DateToUnix(input interface{}) int64 {
18 if input != nil { 14 if input != nil {
19 t := input.(time.Time) 15 t := input.(time.Time)
20 return t.Unix() 16 return t.Unix()
21 17
22 } 18 }
23 return 0 19 return 0
24 } 20 }
25 21
26 func aersDate(unixString string) (string, error) { 22 func EqualQuotes(input string) string {
27 unixTime, err := strconv.ParseInt(unixString, 10, 64)
28 if err != nil {
29 return "", err
30 }
31
32 date := unixToDate(unixTime).String()
33 tokens := strings.Split(date, "-")
34 dateString := tokens[0] + tokens[1] + strings.Split(tokens[2], " ")[0]
35
36 return dateString, nil
37 }
38
39 ////
40 //// STRING UTILITY
41 ////
42
43 // surrondWithSingleQuotes is used when url param is of type string
44 func putQuotes(input string) string {
45 if input != "" { 23 if input != "" {
46 return " = '" + input + "'" 24 return " = '" + input + "'"
47 } 25 }
48 return "" 26 return ""
49 } 27 }
50 28
51 func putLikeQuotes(input string) string { 29 func LikeQuotes(input string) string {
52 if input != "" { 30 if input != "" {
53 return " LIKE UPPER('%" + input + "%')" 31 return " LIKE UPPER('%" + input + "%')"
54 } 32 }
55 return "" 33 return ""
56 } 34 }
57 35
58 36
1 package restutility 1 package restutility
2 2
3 import ( 3 import (
4 "net/http" 4 "net/http"
5 "encoding/json" 5 "encoding/json"
6 ) 6 )
7 7
8 const APIVersion = "/api/v1" 8 var _apiVersion = "/api/v1"
9
10 func SetApiVersion(ver string) string {
11 _apiVersion = ver
12 return _apiVeresion
13 }
9 14
10 //// 15 ////
11 //// ERROR UTILITY 16 //// ERROR UTILITY
12 //// 17 ////
13 18
14 const templateHttpErr500_EN = "An internal server error has occurred." 19 const templateHttpErr500_EN = "An internal server error has occurred."
15 const templateHttpErr500_RS = "Došlo je do greške na serveru." 20 const templateHttpErr500_RS = "Došlo je do greške na serveru."
16 const templateHttpErr400_EN = "Bad request: invalid request body." 21 const templateHttpErr400_EN = "Bad request: invalid request body."
17 const templateHttpErr400_RS = "Neispravan zahtev." 22 const templateHttpErr400_RS = "Neispravan zahtev."
18 23
19 type HttpError struct { 24 type HttpError struct {
20 Error []HttpErrorDesc `json:"error"` 25 Error []HttpErrorDesc `json:"error"`
21 Request string `json:"request"` 26 Request string `json:"request"`
22 } 27 }
23 28
24 type HttpErrorDesc struct { 29 type HttpErrorDesc struct {
25 Lang string `json:"lang"` 30 Lang string `json:"lang"`
26 Desc string `json:"description"` 31 Desc string `json:"description"`
27 } 32 }
28 33
29 func respondWithHttpError(w http.ResponseWriter, 34 func RespondWithHttpError(w http.ResponseWriter,
30 req *http.Request, 35 req *http.Request,
31 code int, 36 code int,
32 httpErr []HttpErrorDesc) { 37 httpErr []HttpErrorDesc) {
33 38
34 err := HttpError{ 39 err := HttpError{
35 Error: httpErr, 40 Error: httpErr,
36 Request: req.Method + " " + req.URL.Path, 41 Request: req.Method + " " + req.URL.Path,
37 } 42 }
38 w.WriteHeader(code) 43 w.WriteHeader(code)
39 json.NewEncoder(w).Encode(err) 44 json.NewEncoder(w).Encode(err)
40 } 45 }
41 46
42 func respondWithHttpError400(w http.ResponseWriter, req *http.Request) { 47 func RespondWithHttpError400(w http.ResponseWriter, req *http.Request) {
43 respondWithHttpError(w, req, http.StatusBadRequest, 48 RespondWithHttpError(w, req, http.StatusBadRequest, []HttpErrorDesc{
44 []HttpErrorDesc{ 49 {Lang: "en", Desc: templateHttpErr400_EN},
45 { 50 {Lang: "rs", Desc: templateHttpErr400_RS},
46 Lang: "en", 51 })
47 Desc: templateHttpErr400_EN,
48 },
49 {
50 Lang: "rs",
51 Desc: templateHttpErr400_RS,
52 },
53 })
54 } 52 }
55 53
56 func respondWithHttpError500(w http.ResponseWriter, req *http.Request) { 54 func RespondWithHttpError500(w http.ResponseWriter, req *http.Request) {
57 respondWithHttpError(w, req, http.StatusInternalServerError, 55 RespondWithHttpError(w, req, http.StatusInternalServerError, []HttpErrorDesc{
58 []HttpErrorDesc{ 56 {Lang: "en", Desc: templateHttpErr500_EN},
59 { 57 {Lang: "rs", Desc: templateHttpErr500_RS},
60 Lang: "en", 58 })
61 Desc: templateHttpErr500_EN,
62 },
63 {
64 Lang: "rs",
65 Desc: templateHttpErr500_RS,
66 },
67 })
68 } 59 }
69 60
70 func deliverPayload(w http.ResponseWriter, payload JSONPayload) { 61 func DeliverPayload(w http.ResponseWriter, payload JSONPayload) {
71 json.NewEncoder(w).Encode(payload) 62 json.NewEncoder(w).Encode(payload)
72 payload.Data = nil 63 payload.Data = nil
73 } 64 }
74 65
75 //// 66 ////
76 //// HANDLER FUNC WRAPPER 67 //// HANDLER FUNC WRAPPER
77 //// 68 ////
78 69
79 // wrapHandlerFunc is as wrapper function for route handlers. 70 // wrapHandlerFunc is as wrapper function for route handlers.
80 // Sets common headers and checks for token validity. 71 // Sets common headers and checks for token validity.
81 func commonHttpWrap(fn http.HandlerFunc) http.HandlerFunc { 72 func HandleFuncWrap(fn http.HandlerFunc) http.HandlerFunc {
82 return func(w http.ResponseWriter, req *http.Request) { 73 return func(w http.ResponseWriter, req *http.Request) {
83 // @TODO: check Content-type header (must be application/json) 74 // @TODO: check Content-type header (must be application/json)
84 // ctype := w.Header.Get("Content-Type") 75 // ctype := w.Header.Get("Content-Type")
85 // if req.Method != "GET" && ctype != "application/json" { 76 // if req.Method != "GET" && ctype != "application/json" {
86 // replyWithHttpError(w, req, http.StatusBadRequest, 77 // replyWithHttpError(w, req, http.StatusBadRequest,
87 // "Not a supported content type: " + ctype) 78 // "Not a supported content type: " + ctype)
88 // } 79 // }
89 80
90 w.Header().Set("Access-Control-Allow-Origin", "*") 81 w.Header().Set("Access-Control-Allow-Origin", "*")
91 w.Header().Set("Access-Control-Allow-Methods", 82 w.Header().Set("Access-Control-Allow-Methods",
92 `POST, 83 `POST,
93 GET, 84 GET,
94 PUT, 85 PUT,
95 DELETE, 86 DELETE,
96 OPTIONS`) 87 OPTIONS`)
97 w.Header().Set("Access-Control-Allow-Headers", 88 w.Header().Set("Access-Control-Allow-Headers",
98 `Accept, 89 `Accept,
99 Content-Type, 90 Content-Type,
100 Content-Length, 91 Content-Length,
101 Accept-Encoding, 92 Accept-Encoding,
102 X-CSRF-Token, 93 X-CSRF-Token,
103 Authorization`) 94 Authorization`)
104 w.Header().Set("Content-Type", "application/json; charset=utf-8") 95 w.Header().Set("Content-Type", "application/json; charset=utf-8")
105 96
106 if req.Method == "OPTIONS" { 97 if req.Method == "OPTIONS" {
107 return 98 return
108 } 99 }
109 100
110 if req.URL.Path != APIVersion + "/token/new" { 101 if req.URL.Path != _apiVersion + "/token/new" {
111 token := req.Header.Get("Authorization") 102 token := req.Header.Get("Authorization")
112 if _, err := parseAPIToken(token); err != nil { 103 if _, err := ParseAPIToken(token); err != nil {
113 respondWithHttpError(w, req, http.StatusUnauthorized, 104 RespondWithHttpError(w, req, http.StatusUnauthorized,
114 []HttpErrorDesc{ 105 []HttpErrorDesc{
115 { 106 {Lang: "en", Desc: "Unauthorized request."},
116 Lang: "en", 107 {Lang: "rs", Desc: "Neautorizovani zahtev."},
117 Desc: "Unauthorized request.",
118 },
119 {
120 Lang: "rs",
121 Desc: "Neautorizovani zahtev.",
122 },
123 }) 108 })
124 return 109 return
125 } 110 }
126 } 111 }
127 112
128 err := req.ParseForm() 113 err := req.ParseForm()
129 if err != nil { 114 if err != nil {
130 respondWithHttpError(w, req, http.StatusBadRequest, 115 RespondWithHttpError(w, req, http.StatusBadRequest,
131 []HttpErrorDesc{ 116 []HttpErrorDesc{
132 { 117 {Lang: "en", Desc: templateHttpErr400_EN},
133 Lang: "en", 118 {Lang: "rs", Desc: templateHttpErr400_RS},
134 Desc: templateHttpErr400_EN,
135 },
136 {
137 Lang: "rs",
138 Desc: templateHttpErr400_RS,
139 },
140 }) 119 })
141 return 120 return
142 } 121 }
143 fn(w, req) 122 fn(w, req)
144 } 123 }
145 } 124 }
146 125
147 //// 126 ////
148 //// NOT FOUND HANDLER 127 //// NOT FOUND HANDLER
149 //// 128 ////
150 129
151 func notFoundHandler(w http.ResponseWriter, req *http.Request) { 130 func NotFoundHandler(w http.ResponseWriter, req *http.Request) {
152 respondWithHttpError(w, req, http.StatusNotFound, 131 RespondWithHttpError(w, req, http.StatusNotFound, []HttpErrorDesc{
153 []HttpErrorDesc{ 132 {Lang: "en", Desc: "Not found."},
154 { 133 {Lang: "rs", Desc: "Traženi resurs ne postoji."},
155 Lang: "en", 134 })
156 Desc: "Not found.",
157 },
158 {
159 Lang: "rs",
tables_utility.go
1 package restutility 1 package restutility
2 2
3 import ( 3 import (
4 "encoding/json" 4 "encoding/json"
5 "errors" 5 "errors"
6 ) 6 )
7 7
8 type TableConfig struct { 8 type TableConfig struct {
9 Tables []Table 9 Tables []Table
10 } 10 }
11 11
12 type Table struct { 12 type Table struct {
13 TableType string `json:"tableType"` 13 TableType string `json:"tableType"`
14 Translations []TableTranslation `json:"translations"` 14 Translations []TableTranslation `json:"translations"`
15 TableFields []Field `json:"tableFields"` 15 TableFields []Field `json:"tableFields"`
16 Correlations []CorrelationField `json:"correlation_fields"` 16 Correlations []CorrelationField `json:"correlation_fields"`
17 IdField string `json:"idField"` 17 IdField string `json:"idField"`
18 } 18 }
19 19
20 type CorrelationField struct { 20 type CorrelationField struct {
21 Result string `json:"result"` 21 Result string `json:"result"`
22 Elements []string `json:"elements"` 22 Elements []string `json:"elements"`
23 Type string `json:"type"` 23 Type string `json:"type"`
24 } 24 }
25 25
26 type TableTranslation struct { 26 type TableTranslation struct {
27 Language string `json:"language"` 27 Language string `json:"language"`
28 FieldsLabels map[string]string `json:"fieldsLabels"` 28 FieldsLabels map[string]string `json:"fieldsLabels"`
29 } 29 }
30 30
31 func (tl TableConfig) LoadTranslations(tableType string) LangMap { 31 func (tl TableConfig) LoadTranslations(tableType string) LangMap {
32 translations := make(LangMap, 0) 32 translations := make(LangMap, 0)
33 33
34 for _, table := range tl.Tables { 34 for _, table := range tl.Tables {
35 if tableType == table.TableType { 35 if tableType == table.TableType {
36 for _, t := range table.Translations { 36 for _, t := range table.Translations {
37 translations[t.Language] = t.FieldsLabels 37 translations[t.Language] = t.FieldsLabels
38 } 38 }
39 } 39 }
40 } 40 }
41 41
42 return translations 42 return translations
43 } 43 }
44 44
45 func (tl TableConfig) LoadFields(tableType string) []Field { 45 func (tl TableConfig) LoadFields(tableType string) []Field {
46 fields := make([]Field, 0) 46 fields := make([]Field, 0)
47 47
48 for _, table := range tl.Tables { 48 for _, table := range tl.Tables {
49 if tableType == table.TableType { 49 if tableType == table.TableType {
50 for _, f := range table.TableFields { 50 for _, f := range table.TableFields {
51 fields = append(fields, f) 51 fields = append(fields, f)
52 } 52 }
53 } 53 }
54 } 54 }
55 55
56 return fields 56 return fields
57 } 57 }
58 58
59 func (tl TableConfig) LoadIdField(tableType string) string { 59 func (tl TableConfig) LoadIdField(tableType string) string {
60 for _, table := range tl.Tables { 60 for _, table := range tl.Tables {
61 if tableType == table.TableType { 61 if tableType == table.TableType {
62 return table.IdField 62 return table.IdField
63 } 63 }
64 } 64 }
65 return "" 65 return ""
66 } 66 }
67 67
68 func (tl TableConfig) LoadCorrelations(tableType string) []CorrelationField { 68 func (tl TableConfig) LoadCorrelations(tableType string) []CorrelationField {
69 resp := make([]CorrelationField, 0) 69 resp := make([]CorrelationField, 0)
70 70
71 for _, table := range tl.Tables { 71 for _, table := range tl.Tables {
72 if tableType == table.TableType { 72 if tableType == table.TableType {
73 for _, f := range table.Correlations { 73 for _, f := range table.Correlations {
74 resp = append(resp, f) 74 resp = append(resp, f)
75 } 75 }
76 } 76 }
77 } 77 }
78 78
79 return resp 79 return resp
80 } 80 }
81 81
82 var _tables TableConfig 82 var _tables TableConfig
83 var _prevProject string 83 var _prevProject string
84 84
85 func loadTablesConfig(jsonbuf []byte) error { 85 func InitTables(jsonbuf []byte) error {
86 json.Unmarshal(jsonbuf, &_tables.Tables) 86 json.Unmarshal(jsonbuf, &_tables.Tables)
87
88 if len(_tables.Tables) == 0 { 87 if len(_tables.Tables) == 0 {
89 return errors.New("tables config is corrupt") 88 return errors.New("tables config is corrupt")
90 } 89 }
91
92 return nil 90 return nil
93 } 91 }
94 92
95 func loadTable(table string) JSONParams { 93 func LoadTable(table string) JSONParams {
96 return NewJSONParams(_tables.LoadTranslations(table), 94 return NewJSONParams(_tables.LoadTranslations(table),
97 _tables.LoadFields(table), 95 _tables.LoadFields(table),
98 _tables.LoadIdField(table), 96 _tables.LoadIdField(table),
99 _tables.LoadCorrelations(table)) 97 _tables.LoadCorrelations(table))
100 } 98 }
101 99
102 100