2023-03-25 14:49:30 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
2024-06-28 20:31:45 +00:00
|
|
|
"github.com/Luzifer/sqlapi/pkg/query"
|
|
|
|
"github.com/Luzifer/sqlapi/pkg/types"
|
2023-03-25 14:49:30 +00:00
|
|
|
"github.com/gofrs/uuid"
|
|
|
|
"github.com/gorilla/mux"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
2024-06-28 20:31:45 +00:00
|
|
|
request []types.Query
|
|
|
|
response []types.QueryResult
|
2023-03-25 14:49:30 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
/*
|
|
|
|
=== REQ
|
|
|
|
[
|
|
|
|
["SELECT * FROM tablename WHERE name = ?", "foobar"]
|
|
|
|
]
|
|
|
|
|
|
|
|
=== RESP
|
|
|
|
[
|
|
|
|
[{"name": "foobar", "age": 25}, {"name": "barfoo", "age": 56}]
|
|
|
|
]
|
|
|
|
*/
|
|
|
|
|
|
|
|
func handleRequest(w http.ResponseWriter, r *http.Request) {
|
|
|
|
var (
|
|
|
|
connID = uuid.Must(uuid.NewV4()).String()
|
|
|
|
database = mux.Vars(r)["database"]
|
|
|
|
logger = logrus.WithFields(logrus.Fields{
|
|
|
|
"conn": connID,
|
|
|
|
"db": database,
|
|
|
|
})
|
|
|
|
|
|
|
|
connError = func(err error, reason string, code int) {
|
|
|
|
logger.WithError(err).Error(reason)
|
2024-06-28 20:31:45 +00:00
|
|
|
http.Error(w, fmt.Sprintf("an error occurred: %s", connID), code)
|
2023-03-25 14:49:30 +00:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
w.Header().Set("Cache-Control", "no-cache")
|
|
|
|
w.Header().Set("X-Conn-ID", connID)
|
|
|
|
|
2024-06-28 20:31:45 +00:00
|
|
|
db, err := connect(database)
|
2023-03-25 14:49:30 +00:00
|
|
|
if err != nil {
|
2024-06-28 20:31:45 +00:00
|
|
|
connError(err, "connecting to server", http.StatusInternalServerError)
|
2023-03-25 14:49:30 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
if err := db.Close(); err != nil {
|
|
|
|
logger.WithError(err).Error("closing db connection")
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
var (
|
|
|
|
req request
|
2024-06-28 20:31:45 +00:00
|
|
|
res types.QueryResult
|
2023-03-25 14:49:30 +00:00
|
|
|
resp response
|
|
|
|
)
|
|
|
|
|
|
|
|
if err = json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
|
|
connError(err, "parsing request", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-06-28 20:31:45 +00:00
|
|
|
for i, qry := range req {
|
|
|
|
if res, err = query.RunQuery(db, qry); err != nil {
|
2023-03-25 14:49:30 +00:00
|
|
|
connError(err, fmt.Sprintf("executing query %d", i), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
2024-06-28 20:31:45 +00:00
|
|
|
resp = append(resp, res)
|
2023-03-25 14:49:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if err = json.NewEncoder(w).Encode(resp); err != nil {
|
|
|
|
connError(err, "encoding response", http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|