Skip to content

Commit e5c8b01

Browse files
committed
Added db connection creation
1 parent 2501f3b commit e5c8b01

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

db.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package main
2+
3+
import (
4+
"database/sql"
5+
"fmt"
6+
_ "github.com/lib/pq"
7+
)
8+
9+
const (
10+
DB_USER = "user"
11+
DB_PASSWORD = "password"
12+
DB_NAME = "dbname"
13+
DB_HOST = "dbname"
14+
DB_PORT = "5432"
15+
DB_SSLMODE = "disabled"
16+
)
17+
18+
func GetDbConnection() (*sql.DB, error) {
19+
dbinfo := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=%s",
20+
DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_NAME, DB_SSLMODE)
21+
db, err := sql.Open("postgres", dbinfo)
22+
if err != nil {
23+
return nil, err
24+
}
25+
err = db.Ping()
26+
if err != nil {
27+
return nil, err
28+
}
29+
return db, nil
30+
}

main.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package main
22

33
import (
4+
"database/sql"
45
"encoding/json"
56
"fmt"
67
"github.com/julienschmidt/httprouter"
@@ -52,11 +53,17 @@ func handler(route *Route) func(http.ResponseWriter, *http.Request, httprouter.P
5253
}
5354
}
5455

56+
var db *sql.DB
57+
5558
func main() {
5659
routes, err := ParseRoutes(".")
5760
if err != nil {
5861
log.Fatal(err)
5962
}
63+
db, err = GetDbConnection()
64+
if err != nil {
65+
log.Fatal(err)
66+
}
6067
router := httprouter.New()
6168
for _, route := range routes {
6269
if route.Method == "GET" {

0 commit comments

Comments
 (0)