start working in the database connection
This commit is contained in:
parent
bd844e3c22
commit
f1f255c3be
|
@ -1,12 +1,16 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
_ "github.com/lib/pq"
|
||||
)
|
||||
|
||||
const version = "1.0.0"
|
||||
|
@ -14,6 +18,9 @@ const version = "1.0.0"
|
|||
type config struct {
|
||||
port int
|
||||
env string
|
||||
db struct {
|
||||
dsn string
|
||||
}
|
||||
}
|
||||
|
||||
type application struct {
|
||||
|
@ -26,10 +33,19 @@ func main() {
|
|||
|
||||
flag.IntVar(&cfg.port, "port", 4000, "API Server Port")
|
||||
flag.StringVar(&cfg.env, "env", "development", "Environment (development|staging|production")
|
||||
flag.StringVar(&cfg.db.dsn, "db-dsn", "postgres://postgres:superpassword@localhost/postgres?sslmode=disable", "PostgreSQL DSN")
|
||||
flag.Parse()
|
||||
|
||||
logger := log.New(os.Stdout, "", log.Ldate|log.Ltime)
|
||||
|
||||
db, err := openDB(cfg)
|
||||
if err != nil {
|
||||
logger.Fatal(err)
|
||||
}
|
||||
|
||||
defer db.Close()
|
||||
logger.Printf("database connection pool established")
|
||||
|
||||
app := &application{
|
||||
config: cfg,
|
||||
logger: logger,
|
||||
|
@ -44,6 +60,23 @@ func main() {
|
|||
}
|
||||
|
||||
logger.Printf("starting %s server on %s", cfg.env, srv.Addr)
|
||||
err := srv.ListenAndServe()
|
||||
err = srv.ListenAndServe()
|
||||
logger.Fatal(err)
|
||||
}
|
||||
|
||||
func openDB(cfg config) (*sql.DB, error) {
|
||||
db, err := sql.Open("postgres", cfg.db.dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
err = db.PingContext(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
|
|
5
go.mod
5
go.mod
|
@ -2,4 +2,7 @@ module greenlight.ergz
|
|||
|
||||
go 1.21
|
||||
|
||||
require github.com/julienschmidt/httprouter v1.3.0 // indirect
|
||||
require (
|
||||
github.com/julienschmidt/httprouter v1.3.0 // indirect
|
||||
github.com/lib/pq v1.10.9 // indirect
|
||||
)
|
||||
|
|
2
go.sum
2
go.sum
|
@ -1,2 +1,4 @@
|
|||
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
|
||||
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
|
|
Loading…
Reference in New Issue