Skip to content

Commit

Permalink
api: move server init to internal/server
Browse files Browse the repository at this point in the history
  • Loading branch information
jsec committed Nov 20, 2024
1 parent dc364ab commit 7da9c47
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 14 deletions.
1 change: 1 addition & 0 deletions Taskfile.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ tasks:
dev:
cmds:
- task: db:up
- cmd: air

image:up:
dir: "{{.TASKFILE_DIR}}/docker"
Expand Down
15 changes: 2 additions & 13 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,12 @@ package main
import (
"context"
"log"
"os"

"github.com/jackc/pgx/v5/pgxpool"
"github.com/jsec/f1-data-hub/internal/server"
)

func main() {
pool, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal("Error getting database connection:", err)
}
defer pool.Close()

server := server.NewServer(pool)

err = server.ListenAndServe()
if err != nil {
log.Fatal("Error starting server:", err)
if err := server.Run(context.Background()); err != nil {
log.Fatal(err)
}
}
21 changes: 20 additions & 1 deletion internal/server/server.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package server

import (
"context"
"fmt"
"net/http"
"os"
"time"

"github.com/jackc/pgx/v5/pgxpool"
Expand All @@ -14,7 +16,7 @@ type Server struct {
db *database.Queries
}

func NewServer(pool *pgxpool.Pool) *http.Server {
func createServer(pool *pgxpool.Pool) *http.Server {
// TODO: move this to an env variable
port := 8080
srv := &Server{
Expand All @@ -32,3 +34,20 @@ func NewServer(pool *pgxpool.Pool) *http.Server {

return server
}

func Run(ctx context.Context) error {
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
return fmt.Errorf("error getting database connection: %w", err)
}
defer pool.Close()

server := createServer(pool)

err = server.ListenAndServe()
if err != nil {
return fmt.Errorf("error starting server:", err)

Check failure on line 49 in internal/server/server.go

View workflow job for this annotation

GitHub Actions / Style

error strings should not end with punctuation or newlines (ST1005)

Check failure on line 49 in internal/server/server.go

View workflow job for this annotation

GitHub Actions / Style

Printf call needs 0 args but has 1 args (SA5009)
}

return nil
}

0 comments on commit 7da9c47

Please sign in to comment.