pass sql.DB

This commit is contained in:
Bel LaPointe
2024-11-12 07:50:57 -07:00
parent 9525032c24
commit 253aeb6e65
3 changed files with 68 additions and 3 deletions

21
main.go
View File

@@ -2,6 +2,8 @@ package main
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"flag"
"io"
@@ -13,6 +15,8 @@ import (
"strings"
"text/template"
"time"
_ "github.com/glebarez/sqlite"
)
var httpc = &http.Client{
@@ -23,8 +27,9 @@ var httpc = &http.Client{
}
type Handler struct {
tmpl *template.Template
target *url.URL
tmpl *template.Template
target *url.URL
idempotency *sql.DB
}
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
@@ -54,10 +59,20 @@ func main() {
p := fs.Int("p", 28080, "port")
t := fs.String("t", "{{ . }}", "template")
y := fs.String("y", "http://localhost:41912", "target")
db := fs.String("db", "/tmp/json-adapter.db", "sqlite db for idempotency")
if err := fs.Parse(os.Args[1:]); err != nil {
panic(err)
}
db, err := sql.Open("sqlite", *db)
if err != nil {
panic(err)
}
defer db.Close()
if err := db.PingContext(context.Background()); err != nil {
panic(err)
}
tmpl, err := template.New("").Parse(*t)
if err != nil {
panic(err)
@@ -68,7 +83,7 @@ func main() {
panic(err)
}
h := Handler{tmpl: tmpl, target: u}
h := Handler{tmpl: tmpl, target: u, idempotency: db}
log.Println("listening on", *p)
if err := http.ListenAndServe(":"+strconv.Itoa(*p), h); err != nil {
panic(err)