Skip to content

Commit 0958a54

Browse files
committed
Added sql queries execution in database and returing json
1 parent e5c8b01 commit 0958a54

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

main.go

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,35 @@ func handler(route *Route) func(http.ResponseWriter, *http.Request, httprouter.P
4545
}
4646
params, err := getRequestParams(r, urlParams)
4747
sql, err := route.Sql(params)
48+
if err != nil && sql != "" {
49+
w.WriteHeader(http.StatusBadRequest)
50+
fmt.Fprint(w, sql)
51+
return
52+
}
53+
if err != nil {
54+
w.WriteHeader(http.StatusInternalServerError)
55+
log.Println(err)
56+
return
57+
}
58+
log.Println(sql)
59+
rows, err := db.Query(sql)
4860
if err != nil {
4961
w.WriteHeader(http.StatusInternalServerError)
62+
log.Println(err)
5063
return
5164
}
52-
fmt.Fprint(w, sql)
65+
defer rows.Close()
66+
var jsonValue string
67+
for rows.Next() {
68+
err := rows.Scan(&jsonValue)
69+
if err != nil {
70+
w.WriteHeader(http.StatusInternalServerError)
71+
log.Println(err)
72+
return
73+
}
74+
fmt.Fprint(w, jsonValue)
75+
}
76+
5377
}
5478
}
5579

@@ -64,6 +88,7 @@ func main() {
6488
if err != nil {
6589
log.Fatal(err)
6690
}
91+
defer db.Close()
6792
router := httprouter.New()
6893
for _, route := range routes {
6994
if route.Method == "GET" {

route.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
"bytes"
55
"encoding/json"
6+
"errors"
67
"fmt"
78
"github.com/xeipuuv/gojsonschema"
89
"strings"
@@ -49,7 +50,7 @@ func (self *Route) Sql(params map[string]interface{}) (string, error) {
4950
return "", err
5051
}
5152
if response != "" {
52-
return response, nil
53+
return response, errors.New("schema validation failed")
5354
}
5455
if !self.Custom {
5556
out.Write([]byte("with response_table as ("))

0 commit comments

Comments
 (0)