paste code generated with chatgpt

This commit is contained in:
2024-09-29 16:56:17 +02:00
parent d3a7290100
commit 570d2acf78
6 changed files with 223 additions and 1 deletions

132
main.go Normal file
View File

@@ -0,0 +1,132 @@
package main
import (
"database/sql"
"fmt"
"html/template"
"log"
"net/http"
"os"
"strconv"
_ "github.com/lib/pq" // PostgreSQL driver
)
var db *sql.DB // Global database connection
// dbConnection initializes the database connection.
func dbConnection() (*sql.DB, error) {
connStr := os.Getenv("DATABASE_URL") // You should set this env var, e.g., postgres://username:password@localhost/dbname?sslmode=disable
return sql.Open("postgres", connStr)
}
// indexHandler serves the HTML form for the query.
func indexHandler(w http.ResponseWriter, r *http.Request) {
tmpl := `
<!DOCTYPE html>
<html>
<head>
<title>Query Form</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
text-align: center;
margin-top: 50px;
}
form {
margin: 0 auto;
max-width: 300px;
padding: 20px;
background-color: white;
border-radius: 10px;
box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
}
input[type="number"], input[type="submit"] {
width: 100%;
padding: 10px;
margin: 5px 0;
border: 1px solid #ccc;
border-radius: 5px;
}
input[type="submit"] {
background-color: #5cb85c;
color: white;
border: none;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #4cae4c;
}
</style>
</head>
<body>
<h1>Query Form</h1>
<form action="/query" method="get">
<label for="param">Enter a number:</label>
<input type="number" id="param" name="param" required>
<input type="submit" value="Submit">
</form>
</body>
</html>
`
t := template.Must(template.New("form").Parse(tmpl))
t.Execute(w, nil)
}
// selectHandler handles HTTP requests and executes a SQL query.
func selectHandler(w http.ResponseWriter, r *http.Request) {
// Get the 'param' query parameter
paramStr := r.URL.Query().Get("param")
if paramStr == "" {
http.Error(w, "Missing 'param' query parameter", http.StatusBadRequest)
return
}
// Convert the param to an integer
param, err := strconv.Atoi(paramStr)
if err != nil {
http.Error(w, "Invalid 'param' query parameter. Must be an integer.", http.StatusBadRequest)
return
}
// Prepare the SQL query to prevent SQL injection
query := "SELECT 42 + $1"
// Execute the query with the provided parameter
var result int
err = db.QueryRow(query, param).Scan(&result)
if err != nil {
log.Printf("Failed to execute query: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// Return the result in a simple HTML response
fmt.Fprintf(w, "<h1>Result: %d</h1>", result)
}
func main() {
var err error
// Initialize the database connection once at startup
db, err = dbConnection()
if err != nil {
log.Fatalf("Failed to connect to the database: %v", err)
}
defer db.Close()
// Define the handler for the `/` route (serves HTML form)
http.HandleFunc("/", indexHandler)
// Define the handler for the `/query` route (executes SQL query)
http.HandleFunc("/query", selectHandler)
// Start the HTTP server
port := ":8080"
log.Printf("Server starting on port %s\n", port)
err = http.ListenAndServe(port, nil)
if err != nil {
log.Fatalf("Server failed to start: %v", err)
}
}