Skip to content

Instantly share code, notes, and snippets.

@alexedwards
Created October 27, 2020 07:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alexedwards/534b79818ac8cb2410762ea33cee91f2 to your computer and use it in GitHub Desktop.
Save alexedwards/534b79818ac8cb2410762ea33cee91f2 to your computer and use it in GitHub Desktop.
Config package with global variable
.
├── config
│ └── config.go
├── go.mod
├── go.sum
├── main.go
└── models
└── books
└── books.go
package books
import (
"bookstore.alexedwards.net/config"
)
type Book struct {
Isbn string
Title string
Author string
Price float32
}
func All() ([]Book, error) {
rows, err := config.DB.Query("SELECT * FROM books")
if err != nil {
return nil, err
}
defer rows.Close()
var bks []Book
for rows.Next() {
var bk Book
err := rows.Scan(&bk.Isbn, &bk.Title, &bk.Author, &bk.Price)
if err != nil {
return nil, err
}
bks = append(bks, bk)
}
if err = rows.Err(); err != nil {
return nil, err
}
return bks, nil
}
package config
import (
"database/sql"
)
var DB *sql.DB
module bookstore.alexedwards.net
go 1.15
require github.com/lib/pq v1.8.0
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"bookstore.alexedwards.net/config"
"bookstore.alexedwards.net/models/books"
_ "github.com/lib/pq"
)
func main() {
var err error
config.DB, err = sql.Open("postgres", "postgres://user:pass@localhost/bookstore")
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/books", booksIndex)
http.ListenAndServe(":3000", nil)
}
func booksIndex(w http.ResponseWriter, r *http.Request) {
bks, err := books.All()
if err != nil {
log.Println(err)
http.Error(w, http.StatusText(500), 500)
return
}
for _, bk := range bks {
fmt.Fprintf(w, "%s, %s, %s, £%.2f\n", bk.Isbn, bk.Title, bk.Author, bk.Price)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment