Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

5 improve config #6

Merged
merged 9 commits into from
Dec 24, 2024
Merged
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
51 changes: 51 additions & 0 deletions .github/workflows/go-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
name: Go Tests

on:
pull_request:
branches:
- main

jobs:
test:
name: Run Go Tests
runs-on: ubuntu-latest

steps:
# Step 1: Checkout the repository code
- name: Checkout code
uses: actions/checkout@v3

# Step 2: Set up Go environment
- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: 1.18 # Specify your Go version here

# Step 3: Cache Go modules to speed up builds
- name: Cache Go modules
uses: actions/cache@v3
with:
path: |
~/.cache/go-build
# Cache the Go modules based on the go.sum file
~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: |
${{ runner.os }}-go-

# Step 4: Install dependencies
- name: Install dependencies
run: go mod tidy

# Step 5: Run tests with coverage
- name: Run Tests
run: |
go test -v ./... -coverprofile=coverage.out

# Step 6: Upload coverage results (optional)
- name: Upload Coverage
if: success()
uses: actions/upload-artifact@v3
with:
name: coverage-report
path: coverage.out
92 changes: 92 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,94 @@
# Binaries
##############################
# Exclude the binary executable
/bin/
/build/
/dist/

# Executable files
*.exe
*.exe~
*.dll
*.so
*.dylib

# Test binaries
*.test

# Coverage files
*.out

# Logs
##############################
*.log

# Environment Variables
##############################
# Exclude environment variable files
.env
.env.local
.env.*.local

# Dependency directories
##############################
# If you are using Go modules, you typically don't need to commit the vendor directory.
vendor/

# Go workspace file
go.work

# IDE and Editor directories
##############################
# Visual Studio Code
.vscode/

# GoLand
.idea/

# Sublime Text
*.sublime-project
*.sublime-workspace

# Vim
*.swp
*.swo

# Emacs
*~

# JetBrains
# User-specific stuff
.idea/*
!.idea/*.iml
!.idea/modules.xml
!.idea/*.xml

# macOS specific files
##############################
.DS_Store

# Windows specific files
##############################
Thumbs.db
ehthumbs.db
Desktop.ini

# Linux specific files
##############################
*~

# Other files and directories to ignore
##############################
# Temporary files
*.tmp
*.temp

# Backup files
*.bak
*.backup

# Documentation generated files
docs/generated/

# Cache directories
.cache/
9 changes: 7 additions & 2 deletions cmd/coupon_service/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,22 @@ import (
"coupon_service/internal/repository/memdb"
"coupon_service/internal/service"
"fmt"
"log"
"time"
)

var (
cfg = config.New()
repo = memdb.New()
)

func main() {
cfg, err := config.New()
if err != nil {
log.Fatal(err)
}

svc := service.New(repo)
fmt.Println(cfg)

server := api.New(cfg.API, svc)
server.Start()
fmt.Println("Starting Coupon service server")
Expand Down
8 changes: 5 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@ require (
github.com/brumhard/alligotor v0.3.3
github.com/gin-gonic/gin v1.7.6
github.com/google/uuid v1.3.0
github.com/urfave/negroni v1.0.0
github.com/joho/godotenv v1.5.1
github.com/pelletier/go-toml v1.9.5
github.com/stretchr/testify v1.7.1
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.0 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect
Expand All @@ -21,10 +24,9 @@ require (
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/testify v1.7.1 // indirect
github.com/ugorji/go/codec v1.2.7 // indirect
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97 // indirect
golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8 // indirect
Expand Down
3 changes: 2 additions & 1 deletion go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
Expand Down Expand Up @@ -77,7 +79,6 @@ github.com/ugorji/go v1.2.7/go.mod h1:nF9osbDWLy6bDVv/Rtoh6QgnvNDpmCalQV5urGCCS6
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0=
github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY=
github.com/urfave/negroni v1.0.0/go.mod h1:Meg73S6kFm/4PpbYdq35yYWoCZ9mS/YSx+lKnmiohz4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97 h1:/UOmuWzQfxxo9UtlXMwuQU8CMgg1eZXqTRwkSQJWKOI=
Expand Down
8 changes: 4 additions & 4 deletions internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ import (
type Service interface {
ApplyCoupon(entity.Basket, string) (*entity.Basket, error)
CreateCoupon(int, string, int) (string, error)
GetCoupons(...string) ([]entity.Coupon, error)
GetCoupons([]string) ([]entity.Coupon, error)
}

type Config struct {
Host string
Port int
Port string `env:"API_PORT" default:"8080"`
Env string `env:"API_ENV" default:"dev"`
}

type API struct {
Expand All @@ -40,7 +40,7 @@ func New[T Service](cfg Config, svc T) API {

func (a API) withServer() API {
a.srv = &http.Server{
Addr: fmt.Sprintf(":%d", a.CFG.Port),
Addr: fmt.Sprintf(":%s", a.CFG.Port),
Handler: a.MUX,
}
return a
Expand Down
11 changes: 10 additions & 1 deletion internal/api/coupon.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,19 @@ func (a *API) Create(c *gin.Context) {

func (a *API) Get(c *gin.Context) {
codes := c.Query("codes")
if codes == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "query parameter 'codes' is required"})
return
}
codeList := strings.Split(codes, ",")
if len(codeList) == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "query parameter 'codes' cannot be empty"})
return
}

coupons, err := a.svc.GetCoupons(codeList...)
coupons, err := a.svc.GetCoupons(codeList)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve coupons"})
return
}
c.JSON(http.StatusOK, coupons)
Expand Down
39 changes: 36 additions & 3 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,52 @@ package config

import (
"coupon_service/internal/api"
"fmt"
"log"
"os"

"github.com/brumhard/alligotor"
"github.com/joho/godotenv"
)

type Config struct {
API api.Config
}

func New() Config {
func New(envPath ...string) (Config, error) {
envFilePath := ""
if len(envPath) > 0 {
envFilePath = envPath[0]
}

if envFilePath != "" {
err := godotenv.Load(envFilePath)
if err != nil {
log.Printf("Warning: failed to load .env file at %s (skipping)", envFilePath)
}
} else {
err := godotenv.Load()
if err != nil {
log.Println("Warning: no .env file found (skipping)")
}
}

cfg := Config{}
cfg.API.Env = getEnv("API_ENV", "dev")
if err := alligotor.Get(&cfg); err != nil {
log.Fatal(err)
return cfg, fmt.Errorf("failed to load config: %w", err)
}

if cfg.API.Port == "" {
return cfg, fmt.Errorf("critical environment variable API_PORT is missing")
}

return cfg, nil
}

func getEnv(key, defaultValue string) string {
if value, exists := os.LookupEnv(key); exists && value != "" {
return value
}
return cfg
return defaultValue
}
Loading
Loading