Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 40 additions & 1 deletion cmd/camp/main.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,26 @@
package main

import (
"encoding/json"
"log"
"net/http"
"os"
"os/signal"
"syscall"

"github.com/codersgyan/camp/config"
"github.com/codersgyan/camp/internal/contact"
"github.com/codersgyan/camp/internal/database"
)

func main() {

cfg, err := config.SetupENV()

if err != nil {
log.Fatal(err)
}

db, err := database.Connect("./camp_data/camp.db")
if err != nil {
log.Fatal(err)
Expand All @@ -24,6 +36,33 @@ func main() {
contactHandler := contact.NewHandler(contactRepository)

http.HandleFunc("POST /api/contacts", contactHandler.Create)
http.HandleFunc("/health", HealthCheckHandler)

// Graceful shutdown

go func() {
if err := http.ListenAndServe(cfg.HttpPort, nil); err != nil {
log.Fatalf("server error: %v", err)
}
log.Printf("server running on this port: %v", cfg.HttpPort)
}()

// Wait for signal (Ctrl+C/kill)
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
<-quit

log.Println("shutting down gracefully...")

}

func HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
resp := map[string]string{
"status": "ok",
}

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)

log.Fatal(http.ListenAndServe(":8080", nil))
json.NewEncoder(w).Encode(resp)
}
27 changes: 27 additions & 0 deletions config/app-config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package config

import (
"errors"
"os"

"github.com/joho/godotenv"
)

type AppConfig struct {
HttpPort string
}

func SetupENV() (cfg *AppConfig, err error) {

godotenv.Load()

httpPort := os.Getenv("HTTP_PORT")

if len(httpPort) < 1 {
return &AppConfig{}, errors.New("env file is not configured properly")
}

return &AppConfig{
HttpPort: httpPort,
}, nil
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ module github.com/codersgyan/camp
go 1.25.2

require github.com/mattn/go-sqlite3 v1.14.32

require github.com/joho/godotenv v1.5.1 // indirect
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/mattn/go-sqlite3 v1.14.32 h1:JD12Ag3oLy1zQA+BNn74xRgaBbdhbNIDYvQUEuuErjs=
github.com/mattn/go-sqlite3 v1.14.32/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=