Skip to content

Commit

Permalink
🛠️ Refactor: Replaced slog by a custom wrapper of zerolog
Browse files Browse the repository at this point in the history
  • Loading branch information
lhbelfanti committed Sep 5, 2024
1 parent 5eb98f2 commit cb2ead4
Show file tree
Hide file tree
Showing 10 changed files with 57 additions and 36 deletions.
32 changes: 25 additions & 7 deletions cmd/api/main.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,41 @@
package main

import (
"context"
"flag"
"fmt"
"log"
"log/slog"
"net/http"
"os"

"github.com/rs/zerolog"

"ahbcc/cmd/api/migrations"
"ahbcc/cmd/api/ping"
"ahbcc/cmd/api/tweets"
"ahbcc/cmd/api/tweets/quotes"
"ahbcc/internal/database"
"ahbcc/internal/log"
"ahbcc/internal/setup"
)

var prodEnv bool

func init() {
flag.BoolVar(&prodEnv, "prod", false, "Run in production environment")
flag.Parse()
}

func main() {
/* --- Dependencies --- */
ctx := context.Background()

logLevel := zerolog.DebugLevel
if prodEnv {
logLevel = zerolog.InfoLevel
}

log.NewCustomLogger(os.Stdout, logLevel)

// Database
pg := setup.Init(database.InitPostgres())
defer pg.Close()
Expand All @@ -32,16 +51,15 @@ func main() {
insertTweets := tweets.MakeInsert(db, insertSingleQuote, deleteOrphanQuotes)

/* --- Router --- */
log.Info(ctx, "Initializing router...")
router := http.NewServeMux()
router.HandleFunc("GET /ping/v1", ping.HandlerV1())
router.HandleFunc("POST /migrations/run/v1", migrations.RunHandlerV1(runMigrations))
router.HandleFunc("POST /tweets/v1", tweets.InsertHandlerV1(insertTweets))
log.Info(ctx, "Router initialized!")

/* --- Server --- */
port := fmt.Sprintf(":%s", os.Getenv("API_PORT"))
slog.Info(fmt.Sprintf("AHBCC server is ready to receive request on port %s", port))
err := http.ListenAndServe(port, router)
if err != nil {
log.Fatalf("Could not start server: %s\n", err.Error())
}
log.Info(ctx, fmt.Sprintf("AHBCC server is ready to receive request on port %s", port))
setup.Must(http.ListenAndServe(port, router))
}
8 changes: 5 additions & 3 deletions cmd/api/migrations/handler.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
package migrations

import (
"log/slog"
"net/http"

"ahbcc/internal/log"
)

const migrationsDir string = "./migrations"

// RunHandlerV1 HTTP Handler of the endpoint /migrations/run/v1
func RunHandlerV1(runMigrations Run) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
err := runMigrations(r.Context(), migrationsDir)
ctx := r.Context()
err := runMigrations(ctx, migrationsDir)
if err != nil {
slog.Error(err.Error())
log.Error(ctx, err.Error())
http.Error(w, FailedToRunMigrations, http.StatusInternalServerError)
return
}
Expand Down
21 changes: 9 additions & 12 deletions cmd/api/migrations/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,15 @@ package migrations
import (
"context"
"fmt"
"log/slog"
"os"
"path/filepath"

"ahbcc/internal/database"
"ahbcc/internal/log"
)

type (

// Run executes the migrations after the database is initialized
Run func(ctx context.Context, migrationsDir string) error
)
// Run executes the migrations after the database is initialized
type Run func(ctx context.Context, migrationsDir string) error

// MakeRun creates a new Run
func MakeRun(db database.Connection, createMigrationsTable CreateMigrationsTable, isMigrationApplied IsMigrationApplied, insertAppliedMigration InsertAppliedMigration) Run {
Expand All @@ -33,20 +30,20 @@ func MakeRun(db database.Connection, createMigrationsTable CreateMigrationsTable
}

if !applied {
fmt.Printf("Executing %s...\n", file)
log.Info(ctx, fmt.Sprintf("Executing %s...\n", file))
err = executeSQLFromFile(ctx, db, file)
if err != nil {
slog.Error(err.Error())
log.Error(ctx, err.Error())
return FailedToExecuteMigration
}
fmt.Printf("Executed %s successfully\n", file)
log.Info(ctx, fmt.Sprintf("Executed %s successfully\n", file))

err = insertAppliedMigration(ctx, file)
if err != nil {
return err
}
} else {
fmt.Printf("Migration file %s already applied\n", file)
log.Info(ctx, fmt.Sprintf("Migration file %s already applied\n", file))
}
}

Expand All @@ -58,13 +55,13 @@ func MakeRun(db database.Connection, createMigrationsTable CreateMigrationsTable
func executeSQLFromFile(ctx context.Context, db database.Connection, filename string) error {
content, err := os.ReadFile(filename)
if err != nil {
slog.Error(err.Error())
log.Error(ctx, err.Error())
return UnableToReadFile
}

_, err = db.Exec(ctx, string(content))
if err != nil {
slog.Error(err.Error())
log.Error(ctx, err.Error())
return UnableToExecuteSQL
}

Expand Down
7 changes: 4 additions & 3 deletions cmd/api/migrations/tracker.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ package migrations
import (
"context"
"errors"

"github.com/jackc/pgx/v5"
"log/slog"

"ahbcc/internal/database"
"ahbcc/internal/log"
)

type (
Expand All @@ -33,7 +34,7 @@ func MakeCreateMigrationsTable(db database.Connection) CreateMigrationsTable {
return func(ctx context.Context) error {
_, err := db.Exec(ctx, query)
if err != nil {
slog.Error(err.Error())
log.Error(ctx, err.Error())
return FailedToCreateMigrationsTable
}

Expand All @@ -56,7 +57,7 @@ func MakeIsMigrationApplied(db database.Connection) IsMigrationApplied {

err := db.QueryRow(ctx, query, migrationName).Scan(&applied)
if errors.Is(err, pgx.ErrNoRows) {
slog.Error(err.Error())
log.Error(ctx, err.Error())
return false, FailedToRetrieveIfMigrationWasApplied
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/api/ping/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ import (
func HandlerV1() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("pong"))
_, _ = w.Write([]byte("pong"))
}
}
10 changes: 6 additions & 4 deletions cmd/api/tweets/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,32 @@ package tweets

import (
"encoding/json"
"log/slog"
"net/http"

"ahbcc/internal/log"
)

// InsertHandlerV1 HTTP Handler of the endpoint /tweets/v1
func InsertHandlerV1(insertTweets Insert) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var tweets []TweetDTO
err := json.NewDecoder(r.Body).Decode(&tweets)
if err != nil {
slog.Error(err.Error())
log.Error(ctx, err.Error())
http.Error(w, InvalidRequestBody, http.StatusBadRequest)
return
}

err = validateBody(tweets)
if err != nil {
slog.Error(err.Error())
log.Error(ctx, err.Error())
http.Error(w, InvalidRequestBody, http.StatusBadRequest)
}

err = insertTweets(r.Context(), tweets)
if err != nil {
slog.Error(err.Error())
log.Error(ctx, err.Error())
http.Error(w, FailedToInsertTweetsIntoDatabase, http.StatusInternalServerError)
return
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/api/tweets/insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ package tweets
import (
"context"
"fmt"
"log/slog"
"strings"

"ahbcc/cmd/api/tweets/quotes"
"ahbcc/internal/database"
"ahbcc/internal/log"
)

// Insert inserts a new TweetDTO into 'tweets' table
Expand Down Expand Up @@ -48,7 +48,7 @@ func MakeInsert(db database.Connection, insertQuote quotes.InsertSingle, deleteO

_, err := db.Exec(ctx, queryToExecute, values...)
if err != nil {
slog.Error(err.Error())
log.Error(ctx, err.Error())
return FailedToInsertTweets
}

Expand Down
4 changes: 2 additions & 2 deletions cmd/api/tweets/quotes/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package quotes
import (
"context"
"fmt"
"log/slog"
"strings"

"ahbcc/internal/database"
"ahbcc/internal/log"
)

// DeleteOrphans when the tweet insertion fails, and that tweets contains a quote,
Expand Down Expand Up @@ -39,7 +39,7 @@ func MakeDeleteOrphans(db database.Connection) DeleteOrphans {

_, err := db.Exec(ctx, queryToExecute, values...)
if err != nil {
slog.Error(err.Error())
log.Error(ctx, err.Error())
return FailedToDeleteOrphanQuotes
}

Expand Down
4 changes: 2 additions & 2 deletions cmd/api/tweets/quotes/insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import (
"errors"

"github.com/jackc/pgx/v5"
"log/slog"

"ahbcc/internal/database"
"ahbcc/internal/log"
)

// InsertSingle inserts a new QuoteDTO into 'quotes' table and returns the PK
Expand All @@ -29,7 +29,7 @@ func MakeInsertSingle(db database.Connection) InsertSingle {
var quoteID int
err := db.QueryRow(ctx, query, quote.IsAReply, quote.TextContent, quote.Images).Scan(&quoteID)
if errors.Is(err, pgx.ErrNoRows) {
slog.Error(err.Error())
log.Error(ctx, err.Error())
return -1, FailedToInsertQuote
}

Expand Down
1 change: 1 addition & 0 deletions compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ services:
context: .
dockerfile: Dockerfile_app
container_name: ahbcc
command: ["/ahbcc", "--prod"]
ports:
- "${APP_EXPOSED_PORT}:${APP_INTERNAL_PORT}"
environment:
Expand Down

0 comments on commit cb2ead4

Please sign in to comment.