Created
December 23, 2019 21:20
-
-
Save marshyon/2c6c7736069cca79dc67fd0362b13827 to your computer and use it in GitHub Desktop.
Go Postgres SQL connect and select
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"fmt" | |
"os" | |
_ "github.com/lib/pq" | |
) | |
var db *sql.DB | |
const ( | |
dbhost = "DBHOST" | |
dbport = "DBPORT" | |
dbuser = "DBUSER" | |
dbpass = "DBPASS" | |
dbname = "DBNAME" | |
) | |
type bookSummary struct { | |
ID int | |
Title string | |
Author string | |
Year string | |
} | |
func main() { | |
bs := make([]bookSummary, 0) | |
config := dbConfig() | |
var err error | |
psqlInfo := fmt.Sprintf("host=%s port=%s user=%s "+ | |
"password=%s dbname=%s sslmode=require", | |
config[dbhost], config[dbport], | |
config[dbuser], config[dbpass], config[dbname]) | |
db, err = sql.Open("postgres", psqlInfo) | |
if err != nil { | |
panic(err) | |
} | |
err = db.Ping() | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("Successfully connected!") | |
rows, err := db.Query(` | |
SELECT | |
id, title, author, year | |
FROM | |
books`) | |
if err != nil { | |
panic(err) | |
} | |
defer rows.Close() | |
for rows.Next() { | |
book := bookSummary{} | |
err = rows.Scan( | |
&book.ID, | |
&book.Title, | |
&book.Author, | |
&book.Year, | |
) | |
if err != nil { | |
panic(err) | |
} | |
bs = append(bs, book) | |
} | |
err = rows.Err() | |
if err != nil { | |
panic(err) | |
} | |
for _, b := range bs { | |
fmt.Printf(" ID : [%d]\n", b.ID) | |
fmt.Printf(" Title : [%s]\n", b.Title) | |
fmt.Printf("Author : [%s]\n", b.Author) | |
fmt.Printf(" Year : [%s]\n\n", b.Year) | |
} | |
} | |
func dbConfig() map[string]string { | |
conf := make(map[string]string) | |
host, ok := os.LookupEnv(dbhost) | |
if !ok { | |
panic("DBHOST environment variable required but not set") | |
} | |
port, ok := os.LookupEnv(dbport) | |
if !ok { | |
panic("DBPORT environment variable required but not set") | |
} | |
user, ok := os.LookupEnv(dbuser) | |
if !ok { | |
panic("DBUSER environment variable required but not set") | |
} | |
password, ok := os.LookupEnv(dbpass) | |
if !ok { | |
panic("DBPASS environment variable required but not set") | |
} | |
name, ok := os.LookupEnv(dbname) | |
if !ok { | |
panic("DBNAME environment variable required but not set") | |
} | |
conf[dbhost] = host | |
conf[dbport] = port | |
conf[dbuser] = user | |
conf[dbpass] = password | |
conf[dbname] = name | |
return conf | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment