Skip to content

Commit

Permalink
detect DATABASE_URL that consist of postgres
Browse files Browse the repository at this point in the history
  • Loading branch information
jackii committed Dec 24, 2024
1 parent 3dcf9b1 commit 8638c61
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
############################
# STEP 1 build executable binary
############################
FROM golang:alpine AS builder
FROM golang:1.19.10-alpine3.18 AS builder
RUN apk update && apk add --no-cache git gcc libc-dev openssl && go install github.com/gobuffalo/packr/packr@latest
WORKDIR $GOPATH/src/securitybunker/databunker/src/
COPY src/go.mod ./deps
Expand Down
17 changes: 17 additions & 0 deletions src/storage/pgsql-storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
Expand All @@ -24,6 +25,22 @@ type PGSQLDB struct {
}

func (dbobj PGSQLDB) getConnectionString(dbname *string) string {
databaseURL := os.Getenv("DATABASE_URL")
if len(databaseURL) > 0 {
u, err := url.Parse(databaseURL)
if err == nil && u.Scheme == "postgres" {
// Extract user info, host, port, and dbname from the URL
user := u.User.Username()
pass, _ := u.User.Password()
host := u.Hostname()
port := u.Port()
dbname := strings.TrimPrefix(u.Path, "/")

return fmt.Sprintf("user='%s' password='%s' host='%s' port='%s' dbname='%s'",
user, pass, host, port, dbname)
}
}

user := os.Getenv("PGSQL_USER_NAME")
pass := os.Getenv("PGSQL_USER_PASS")
host := os.Getenv("PGSQL_HOST")
Expand Down
13 changes: 12 additions & 1 deletion src/storage/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package storage
import (
"go.mongodb.org/mongo-driver/bson"
"net/http"
"net/url"
"os"
)

Expand Down Expand Up @@ -104,8 +105,18 @@ type BackendDB interface {
}

func getDBObj() BackendDB {
host := os.Getenv("MYSQL_HOST")
var db BackendDB
databaseURL := os.Getenv("DATABASE_URL")
// Check if DATABASE_URL is set and is a PostgreSQL URL
if len(databaseURL) > 0 {
u, err := url.Parse(databaseURL)
if err == nil && u.Scheme == "postgres" {
db = &PGSQLDB{}
return db
}
}

host := os.Getenv("MYSQL_HOST")
if len(host) > 0 {
db = &MySQLDB{}
return db
Expand Down

0 comments on commit 8638c61

Please sign in to comment.