Database

  • Kita sudah pernah mempelajari database

  • Update .env untuk menambahkan konfigurasi database

PORT = 7070
POSTGRES_HOST = localhost
POSTGRES_PORT = 5432
POSTGRES_USER = postgres
POSTGRES_PASSWORD = pass
POSTGRES_DB = drivers
  • Buat file lib/database/postgres/postgres.go

package postgres

import (
    "context"
    "database/sql"
    "fmt"
    "os"
    "strconv"
)

// Open database commection
func Open() (*sql.DB, error) {
    var db *sql.DB
    port, err := strconv.Atoi(os.Getenv("POSTGRES_PORT"))
    if err != nil {
        return db, err
    }

    return sql.Open("postgres",
        fmt.Sprintf(
            "host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
            os.Getenv("POSTGRES_HOST"), port, os.Getenv("POSTGRES_USER"),
            os.Getenv("POSTGRES_PASSWORD"), os.Getenv("POSTGRES_DB"),
        ),
    )
}

// StatusCheck returns nil if it can successfully talk to the database. It
// returns a non-nil error otherwise.
func StatusCheck(ctx context.Context, db *sql.DB) error {

    // Run a simple query to determine connectivity. The db has a "Ping" method
    // but it can false-positive when it was previously able to talk to the
    // database but the database has since gone away. Running this query forces a
    // round trip to the database.
    const q = `SELECT true`
    var tmp bool
    return db.QueryRowContext(ctx, q).Scan(&tmp)
}
  • Buat file schema/migrate.go

  • Buat file schema/seed.go

  • Buat file cmd/cli.go

  • Buat database drivers

  • Jalankan go run cmd/cli.go migrate

  • Update file server.go untuk membuat koneksi database

  • Update server.go untuk mengaupdate roting dengan menginject db ke service

  • Update server.go service handler agar mempunyai proprety db

  • Update file server.go untuk membuat fungsi logError

  • Update file server.go untuk mengupdate fungsi List

  • Update file server.go untuk mengupdate fungsi Create

  • Update file server.go untuk mengupdate fungsi Update

  • Update file server.go untuk mengupdate fungsi Delete

  • Test create dengan perintah grpcurl -plaintext -import-path ~/jackyhtg/skeleton/proto -proto ~/jackyhtg/skeleton/proto/drivers/driver_service.proto -d '{"name": "jacky", "phone": "08172221", "licence_number": "1234", "company_id": "UAT", "company_name": "Universal Alabama Tahoma"}' localhost:7070 skeleton.DriversService.Create

  • Tes list dengan perintah grpcurl -import-path ~/jackyhtg/skeleton/proto -proto ~/jackyhtg/skeleton/proto/drivers/driver_service.proto -plaintext localhost:7070 skeleton.DriversService.List

  • Tes delete denagn perintah grpcurl -plaintext -import-path ~/jackyhtg/skeleton/proto -proto ~/jackyhtg/skeleton/proto/drivers/driver_service.proto -d '{"id":"3a36a71f-021c-4465-9fda-36699b320855"}' localhost:7070 skeleton.DriversService.Delete

Ini adalah kode keseluruhan server.go

Last updated

Was this helpful?