Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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