To create a simple HTTP server in Go that saves all HTTP requests to a SQLite database, follow these steps:
-
Install dependencies: Make sure you have Go (version 1.13 or higher) and SQLite3 installed on your system.
-
Create a new file (e.g., main.go) and add the following code:
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"time"
_ "github.com/mattn/go-sqlite3"
)
type Request struct {
ID int
Method string
URI string
RemoteIP string
Time time.Time
}
func main() {
// Connect to the SQLite database
db, err := sql.Open("sqlite3", "requests.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Create the table if it doesn't exist
_, err = db.Exec("CREATE TABLE IF NOT EXISTS requests (ID INTEGER PRIMARY KEY, Method TEXT, URI TEXT, RemoteIP TEXT, Time TEXT)")
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
now := time.Now()
// Create the request struct with the current request data
req := Request{
Method: r.Method,
URI: r.URL.Path,
RemoteIP: r.RemoteAddr,
Time: now,
}
// Insert the request into the database
stmt, err := db.Prepare("INSERT INTO requests (Method, URI, RemoteIP, Time) VALUES (?, ?, ?, ?)")
if err != nil {
log.Println(err)
return
}
defer stmt.Close()
_, err = stmt.Exec(req.Method, req.URI, req.RemoteIP, now.Format("2006-01-02 15:04:05"))
if err != nil {
log.Println(err)
return
}
// Serve the default response
fmt.Fprintf(w, "HTTP server with request logging")
}
This code snippet creates a Request struct to hold HTTP request details. The main function initializes and connects to the SQLite database, creates the table if it doesn't exist, and registers our handler for the root path "/".
The handler function stores request details into a Request struct, inserts it into the database, and returns the desired response.
Now, you can run the program using go run main.go to start the HTTP server, and all HTTP requests will be logged into the requests.db SQLite database.