Running Postgres Locally with Docker
Before we set about implementing the database package, we’ll need a database running somewhere to connect to and create our tables on. Let’s kick off a locally running database using docker:
$ docker run --name rocket-inventory-db -e POSTGRES_PASSWORD=postgres -p 5432:5432 -d postgres
Awesome, if we do docker ps
we should now be able to see our locally running docker container running our Postgres database!
Implementing our DB package
package db
import (
"fmt"
"os"
"github.com/TutorialEdge/go-grpc-services-course/internal/rocket"
"github.com/jmoiron/sqlx"
)
// DB
type Store struct {
db *sqlx.DB
}
// New - returns a new Store
func New() (Store, error) {
dbUsername := os.Getenv("DB_USERNAME")
dbPassword := os.Getenv("DB_PASSWORD")
dbHost := os.Getenv("DB_HOST")
dbTable := os.Getenv("DB_TABLE")
dbPort := os.Getenv("DB_PORT")
connectString := fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=disable", dbHost, dbPort, dbUsername, dbTable, dbPassword)
db, err := sqlx.Connect("postgres", connectString)
if err != nil {
return Store{}, err
}
return Store{
db: db,
}, nil
}
// GetRocketByID - returns a rocket from the database by a given ID
func (s Store) GetRocketByID(id string) (rocket.Rocket, error) {
return rocket.Rocket{}, nil
}
// InsertRocket - inserts a new rocket into the database
func (s Store) InsertRocket(rkt rocket.Rocket) (rocket.Rocket, error) {
return rocket.Rocket{}, nil
}
// DeleteRocket - deletes a rocket from the database by it's ID
func (s Store) DeleteRocket(id string) error {
return nil
}
Awesome, let’s now look at how we can instantiate a new Store within the main.go
file and wire this into a Rocket service.
Conclusion
Awesome, in this video, we’ve been able to succesfully implement our database package and wire it into our rocket service within the main.go
file.
With the business critical section of our application out of the way, we can now start to focus on the transport layer of our application!