-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.go
415 lines (342 loc) · 8.99 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
package main
import (
"fmt"
"net/http"
"strings"
_ "encoding/json"
_ "log"
)
type ResponseType int
const (
StringArray ResponseType = 0
DictArray = 1
Dict = 2
)
type RequestType int
const (
DatabasesList RequestType = 0
TablesList = 1
WholeTable = 2
TableQuery = 3
InsertElement = 4
TableElement = 5
RemoveElement = 6
CreateTable = 7
CreateDatabase = 8
RemoveTable = 9
RemoveDatabase = 10
)
type ConditionOperation int
const (
Less ConditionOperation = 0
LessOrEqual = 1
More = 2
MoreOrEqual = 3
Equal = 4
)
type ParameterKey string
const (
DatabaseName = "DatabaseName"
TableName = "TableName"
ElementIdentifier = "ElementIdentifier"
)
type TableField struct {
fieldName string `json:"field,omitempty"`
kind string `json:"type, omitempty"`
}
func main() {
fmt.Println(startServer())
}
func startServer() error {
http.HandleFunc("/databases/", parse)
return http.ListenAndServe("127.0.0.1:8080", nil)
}
func parse(w http.ResponseWriter, r *http.Request) {
var responseType ResponseType
var requestType RequestType
u := strings.Split(r.URL.Path, "/")
l := len(u)
if u[l-1] == "" {
l--
}
params := make(map[string]string)
cc := []condition{}
switch r.Method {
case "GET":
if l == 2 { // Databases list
responseType = StringArray
requestType = DatabasesList
} else if l == 3 { // DB Tables list
responseType = StringArray
requestType = TablesList
params[DatabaseName] = u[2]
} else if l == 4 { // DB Concrete table or query
conditionsQuery := r.URL.Query().Get("q")
if len(conditionsQuery) > 0 {
responseType = DictArray
requestType = TableQuery
cc = parseCondition(conditionsQuery)
} else {
responseType = DictArray
requestType = WholeTable
}
params[DatabaseName] = u[2]
params[TableName] = u[3]
} else if l == 5 { // single table element
params[DatabaseName] = u[2]
params[TableName] = u[3]
params[ElementIdentifier] = u[4]
requestType = TableElement
responseType = Dict
}
case "POST":
if l == 3 { // create DB
responseType = Dict
requestType = CreateDatabase
params[DatabaseName] = u[2]
} else if l == 4 { // insert element
urlParams := r.URL.Query()
if len (urlParams) > 0 {
responseType = Dict
requestType = InsertElement
params[DatabaseName] = u[2]
params[TableName] = u[3]
for key, value := range urlParams {
params[key] = value[0]
}
} else {
// TODO: report error to a user
}
} else if l == 5 { // create table
responseType = Dict
requestType = CreateTable
params[DatabaseName] = u[2]
params[TableName] = u[3]
urlParams := r.URL.Query()
if len(urlParams) > 0 {
for key, value := range urlParams {
params[key] = value[0]
}
} else {
// TODO: report error to a user
}
}
fmt.Println("POST ", r.URL.Path)
case "DELETE":
if l == 3 { // del DB
responseType = Dict
requestType = RemoveDatabase
params[DatabaseName] = u[2]
} else if l == 4 { // Del table
responseType = Dict
requestType = RemoveTable
params[DatabaseName] = u[2]
params[TableName] = u[3]
} else if l == 5 { // Del row from table
responseType = Dict
requestType = RemoveElement
params[DatabaseName] = u[2]
params[TableName] = u[3]
params[ElementIdentifier] = u[4]
}
fmt.Println("DELETE ", r.URL.Path)
}
fmt.Println(responseType, requestType, params, cc)
// query(responseType, requestType, params, cc)
}
// 127.0.0.1:8080/databases/1/2/param1 = value1¶m2 = value2
type condition struct {
name string
operation ConditionOperation
value string
}
func clearEmptyStrings (originalSlice []string) []string {
clearSlice := make([]string, len(originalSlice))
nonEmptyStringsCount := 0
for _, t := range originalSlice {
if len(t) > 0 && t != " " {
clearSlice[nonEmptyStringsCount] = t
nonEmptyStringsCount += 1
}
}
return clearSlice[:nonEmptyStringsCount]
}
func parseCondition(conditionStr string) []condition {
rawConditions := strings.Split(conditionStr, " and ")
cc := make([]condition, len(rawConditions))
mainLoop:
for i, rawCondition := range rawConditions {
components := clearEmptyStrings(strings.Split(rawCondition, " "))
if len(components) < 3 {
continue mainLoop
}
fieldName := components[0]
value := components[2]
var operation ConditionOperation
switch components[1] {
case "mt":
operation = More
case "lt":
operation = Less
case "mgt":
operation = MoreOrEqual
case "lgt":
operation = LessOrEqual
case "equ":
operation = Equal
default:
continue mainLoop
}
cc[i] = condition { fieldName, operation, value }
}
return cc
}
func query(responseType int, requestType int, params map[string]string, conditions []condition) string {
db, err := sql.Open("postgres", "postgres://postgres:@127.0.0.1:5432/postgres?sslmode=disable") // коннект к локальной бд
if err != nil {
log.Fatalf("Can't connect to database: %s", err)
}
var c condition //
var tablename string //намиенование бд, которую необходимо вывести
var dbname string //намиенование бд, которую необходимо вывести
switch responseType {
case 1: //StringArray
switch requestType {
case 0: //DatabasesList
QuerryDatabaseList := "SELECT * FROM pg_database;" // запрос по вывводу всех БД в postgree
rows, err := db.Query(QuerryDatabaseList)
if err != nil {
panic(err)
}
defer rows.Close()
//вывод
case 1: //TablesList
for key, value := range params {
if key == "DatabaseName" {
dbname = value
}
}
QuerryTableList := fmt.Sprintf("SELECT table_name FROM %s", string(dbname)) // запрос по вывводу всех таблиц в postgree
rows, err := db.Query(QuerryTableList)
if err != nil {
panic(err)
}
defer rows.Close()
//вывод
}
case 2: //DictArray
switch requestType {
case 2: //WholeTable
for key, value := range params {
if key == "TableName" {
tablename = value
}
}
QuerryWholeTable := fmt.Sprintf("SELECT * FROM %s", string(tablename))
rows, err := db.Query(QuerryWholeTable)
if err != nil {
panic(err)
}
defer rows.Close()
//вывод
case 3: //TableQuery
o := operator(c.operator) // получаем оператор в значении от int
for key, value := range params {
if key == "TableName" {
tablename = value
}
}
QuerryTableQuery := fmt.Sprintf("SELECT * FROM %s WHERE %s %s %i", tablename, c.fieldName, o, c.value) //имя поля, оператор, значение
rows, err := db.Query(QuerryTableQuery)
if err != nil {
panic(err)
}
defer rows.Close()
}
case 3: //Dict
switch requestType {
case 4: //InsertElement
for key, value := range params {
if key == "TableName" {
tablename = value
}
}
QuerryInsertElement := fmt.Sprintf("INSERT INTO %s (%s) VALUES %i", tablename, c.fieldName, c.value)
case 5: //TableElement
o := operator(c.operator) // получаем оператор в значении от int
for key, value := range params {
if key == "TableName" {
tablename = value
}
}
QuerryTableElement := fmt.Sprintf("SELECT %s FROM %s WHERE %s = %i", tablename, c.fieldName, c.value)
rows, err := db.Query(QuerryTableElement)
if err != nil {
panic(err)
}
defer rows.Close()
case 6: //RemoveElement
o := operator(c.operator)
for key, value := range params {
if key == "TableName" {
tablename = value
}
}
QueryRemoveElement := fmt.Sprintf("DELETE FROM %s WHERE %s %s %i", tablename, c.fieldName, o, c.value)
rows, err := db.Query(QueryRemoveElement)
if err != nil {
panic(err)
}
defer rows.Close()
case 7: //Create Table
for key, value := range params {
if key == "TableName" {
tablename = value
}
}
QueryCreateTable := fmt.Sprintf("CREATE TABLE %s (%s)", tablename, c.fieldName)
rows, err := db.Query(QueryCreateTable)
if err != nil {
panic(err)
}
defer rows.Close()
case 8: //CreateDatabase
for key, value := range params {
if key == "DatabaseName" {
dbname = value
}
}
QueryCreateDatabase := fmt.Sprintf("CREATE DATABASE %s", dbname)
rows, err := db.Query(QueryCreateDatabase)
if err != nil {
panic(err)
}
defer rows.Close()
case 9: //RemoveTable
for key, value := range params {
if key == "TableName" {
tablename = value
}
}
QuerryRemoveTable := fmt.Sprintf("DROP TABLE %s", tablename)
rows, err := db.Query(QuerryRemoveTable)
if err != nil {
panic(err)
}
defer rows.Close()
case 10: //RemoveDatabase
for key, value := range params {
if key == "DatabaseName" {
dbname = value
}
}
QueryCreateDatabase := fmt.Sprintf("DROP DATABASE %s", dbname)
rows, err := db.Query(QueryCreateDatabase)
if err != nil {
panic(err)
}
defer rows.Close()
}
}
return "" // вывод?
}