Made Changes To Use a pgx Connection Pool

This commit is contained in:
Annika Merris 2024-02-05 17:05:02 -05:00
parent c327b571f6
commit c1231d487a
5 changed files with 45 additions and 21 deletions

22
main.go
View file

@ -9,7 +9,7 @@ import (
"forgejo.merr.is/annika/isl-api/Controllers"
"forgejo.merr.is/annika/isl-api/Services"
"forgejo.merr.is/annika/isl-api/sql/powerItem"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/julienschmidt/httprouter"
"github.com/spf13/viper"
)
@ -26,6 +26,7 @@ func main() {
deps.router.HandlerFunc("GET", "/", index)
fmt.Printf("Preparing to listen on `:%v`\n", conf.HttpPort)
err := http.ListenAndServe(fmt.Sprintf(":%v", conf.HttpPort), deps.router)
log.Fatal(err)
}
@ -49,7 +50,7 @@ func setupConfig() {
type dependencies struct {
router *httprouter.Router
postgresConnection *pgx.Conn
postgresConnection *pgxpool.Pool
context context.Context
powerItemQuerier *powerItem.DBQuerier
powerItemService *Services.PowerItemService
@ -60,8 +61,16 @@ func (d *dependencies) initializeDependencies() error {
var err error
d.router = httprouter.New()
d.router.GlobalOPTIONS = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Access-Control-Request-Method") != "" {
header := w.Header()
header.Set("Access-Control-Allow-Methods", header.Get("Allow"))
header.Set("Access-Control-Allow-Headers", "Cache-Control, Expires, Pragma")
header.Set("Access-Control-Allow-Origin", "*")
}
})
d.context = context.Background()
d.postgresConnection, err = pgx.Connect(d.context, conf.ConnectionString)
d.postgresConnection, err = pgxpool.Connect(d.context, conf.ConnectionString)
if err != nil {
return err
}
@ -71,6 +80,13 @@ func (d *dependencies) initializeDependencies() error {
return nil
}
func MiddleCORS(next httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
w.Header().Set("Access-Control-Allow-Origin", "*")
next(w, r, ps)
}
}
func index(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Index")
}