cspj-application/server/main.go

95 lines
2.1 KiB
Go
Raw Normal View History

2024-11-11 15:43:09 +08:00
package main
import (
"context"
"fmt"
"io"
"log"
"net/http"
"github.com/jackc/pgx/v5/pgxpool"
)
// db connection info
// !MIGHT CHANGE
const (
host = "localhost"
port = 5432
user = "asdfuser"
password = "asdfpassword"
dbname = "asdfdb"
)
var pool *pgxpool.Pool
// initialize connection to db
func connectToDb() (*pgxpool.Pool, error) {
// this server is intended to be ran on the same system as the db
dbUrl := fmt.Sprintf("postgresql://%s:%s@%s:%d/%s", user, password, host, port, dbname)
config, err := pgxpool.ParseConfig((dbUrl))
if err != nil {
return nil, fmt.Errorf("unable to parse data URL: %w", err)
}
pool, err := pgxpool.NewWithConfig(context.Background(), config)
if err != nil {
return nil, fmt.Errorf("unable to create connection pool: %w", err)
}
log.Println("Connected to DB :)")
return pool, nil
}
// take http reqeust body as raw sql and pass to db
func executeSql(w http.ResponseWriter, r *http.Request) {
// read the request body
sqlQuery, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
// execute the sql query without any sanitization
rows, err := pool.Query(context.Background(), string(sqlQuery))
if err != nil {
http.Error(w, "Query execution error", http.StatusInternalServerError)
return
}
defer rows.Close()
// prepare the response by iterating over the returned rows
var response string
for rows.Next() {
values, err := rows.Values()
if err != nil {
http.Error(w, "Error reading query result", http.StatusInternalServerError)
return
}
response += fmt.Sprintf("%v\n", values)
}
// send the response to the client
w.Write([]byte(response))
}
// setup the http server
func serveApi() {
http.HandleFunc("/executeSql", executeSql)
log.Println("Unsecure server is running on http://localhost:3001")
if err := http.ListenAndServe(":3001", nil); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}
func main() {
var err error
pool, err = connectToDb()
if err != nil {
log.Fatalf("Failed to connect to db: %v", err)
}
defer pool.Close()
serveApi()
}