Skip to content

Commit

Permalink
Refactor/refactor codebase (#1)
Browse files Browse the repository at this point in the history
* refactor: added verifications, ecr image build script, refactored logger logic and code base
  • Loading branch information
KostLinux authored Oct 27, 2024
1 parent a180c90 commit dfe0411
Show file tree
Hide file tree
Showing 16 changed files with 306 additions and 91 deletions.
14 changes: 14 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Basic set up for three package managers
version: 2
updates:
# Maintain dependencies for Composer
- package-ecosystem: "gomod"
directory: "./"
reviewers:
- "Matrix278"
- "KostLinux"
schedule:
interval: "weekly"
commit-message:
prefix: '[Go Modules]'
include: scope
10 changes: 10 additions & 0 deletions .github/release-drafter.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
name-template: 'v$RESOLVED_VERSION'
tag-template: 'v$RESOLVED_VERSION'
change-template: '- $TITLE @$AUTHOR (#$NUMBER)'
change-title-escapes: '\<*_&'
template: |
# What's Changed
$CHANGES
**Full Changelog**: https://github.com/$OWNER/$REPOSITORY/compare/$PREVIOUS_TAG...v$RESOLVED_VERSION
76 changes: 76 additions & 0 deletions .github/workflows/verify.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
name: Verify & Release
on:
pull_request:
types:
- opened
- synchronize
- edited
- closed
push:
branches:
- '*'
tags:
- 'v[0-9]+.[0-9]+.[0-9]+'

env:
GOPROXY: https://proxy.golang.org

permissions:
contents: write
packages: read
statuses: write
pull-requests: write

jobs:
verify_quality:
name: Verify Code Quality
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- uses: actions/setup-go@v5
with:
go-version: '1.22'

- name: golangci-lint
uses: golangci/golangci-lint-action@v4
with:
version: v1.56.2
working-directory: ./
only-new-issues: false
args: --concurrency=16 --timeout=5m --out-format=github-actions --issues-exit-code=1
skip-cache: false
skip-pkg-cache: true

verify_functionality:
name: Verify Code Functionality
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- uses: actions/setup-go@v5
with:
go-version: '1.22'

- name: Verify functionality
run: go test -v ./...

publish_release:
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
needs:
- verify_quality
- verify_functionality
runs-on: ubuntu-latest
steps:
- name: Set version env
run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV

- uses: release-drafter/release-drafter@v6
with:
disable-autolabeler: true
name: ${{ env.RELEASE_VERSION }}
tag: ${{ env.RELEASE_VERSION }}
version: ${{ env.RELEASE_VERSION }}
publish: false
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@
benchmarks/
51 changes: 51 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
run:
concurrency: 4
deadline: 5m
tests: true

linters-settings:
gocyclo:
min-complexity: 20

linters:
disable-all: true
enable:
- asasalint
- asciicheck
- bidichk
- bodyclose
- dogsled
- durationcheck
- errcheck
- errchkjson
- forbidigo
- gocognit
- gocritic
- godox
- gofmt
- gofumpt
- goimports
- goprintffuncname
- gosimple
- govet
- ineffassign
- misspell
- nakedret
- nestif
- nilerr
- nonamedreturns
- prealloc
- predeclared
- revive
- staticcheck
- stylecheck
- tenv
- typecheck
- unconvert
- unparam
- unused
- usestdlibvars
- whitespace

issues:
max-same-issues: 0
13 changes: 13 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
run:
go run main.go

mod-vendor:
go mod vendor

linter:
@golangci-lint run

gosec:
@gosec -quiet ./...

validate: linter gosec
5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,10 +126,9 @@ func main() {
}
}
```
## Logs example at CloudWatch

## Benchmarks


![CloudWatch Logs](assets/cloudwatch.png)

## License

Expand Down
Binary file added assets/cloudwatch.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions cmd/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ COPY . .
RUN go mod download

# Build the Go app
RUN go build -o main .
RUN GOOS=linux GOARCH=amd64 go build -o main .

# Start a new stage from scratch
FROM alpine:latest
Expand All @@ -23,4 +23,4 @@ COPY --from=builder /app/main /app/main
EXPOSE 8080

# Command to run the executable
ENTRYPOINT ["/app/main"]
ENTRYPOINT ["/app/main"]
34 changes: 34 additions & 0 deletions cmd/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/bin/bash

# Source environment variables
source ~/dev/lookinlabs/terraform/platform-tf/.env.production

# Define the image name and tag
IMAGE_NAME="public.ecr.aws/c2w5h6c4/go-logger-middleware"
IMAGE_TAG="latest"

# Build the Docker image without using the cache
echo "Building Docker image without cache..."
docker build --no-cache -t ${IMAGE_NAME}:${IMAGE_TAG} .
if [ $? -ne 0 ]; then
echo "Failed to build Docker image"
exit 1
fi

# Reauthenticate with AWS ECR
echo "Authenticating with AWS ECR..."
aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/c2w5h6c4
if [ $? -ne 0 ]; then
echo "Failed to authenticate with AWS ECR"
exit 1
fi

# Push the Docker image
echo "Pushing Docker image..."
docker push ${IMAGE_NAME}:${IMAGE_TAG}
if [ $? -ne 0 ]; then
echo "Failed to push Docker image"
exit 1
fi

echo "Docker image pushed successfully"
4 changes: 3 additions & 1 deletion cmd/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,7 @@ go 1.23.2

require (
github.com/go-chi/chi/v5 v5.1.0
github.com/lookinlabs/go-logger-middleware v0.0.0-20241023154743-cacce64726f3
github.com/lookinlabs/go-logger-middleware v0.0.0-00010101000000-000000000000
)

replace github.com/lookinlabs/go-logger-middleware => ../
2 changes: 0 additions & 2 deletions cmd/go.sum
Original file line number Diff line number Diff line change
@@ -1,4 +1,2 @@
github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw=
github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/lookinlabs/go-logger-middleware v0.0.0-20241023154743-cacce64726f3 h1:FqaC99m8pfUtES08uMX6TWXq6ubo2B+0zHWDDMKvOxk=
github.com/lookinlabs/go-logger-middleware v0.0.0-20241023154743-cacce64726f3/go.mod h1:sLQMeTuFt+ZV367AHHYnGgGtbGwdqEB01Inrg/UH+BQ=
54 changes: 22 additions & 32 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,56 +4,46 @@ import (
"encoding/json"
"log"
"net/http"
"os"

"github.com/lookinlabs/go-logger-middleware"
"time"

"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)

func main() {
// Initialize the logger middleware
sensitiveFields := []string{"password", "token"}
appLogger := log.New(os.Stdout, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
loggerMiddleware := logger.NewLoggerMiddleware(sensitiveFields, appLogger)

// Create a Chi router
r := chi.NewRouter()
r.Use(middleware.Logger)

// Use the built-in Chi middleware
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Recoverer)

// Use the custom logger middleware
r.Use(loggerMiddleware.Middleware)

// Define a simple GET endpoint
r.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
})

// Define a POST endpoint to test sanitization
r.Post("/test", func(w http.ResponseWriter, r *http.Request) {
var requestBody map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
if _, err := w.Write([]byte("Hello, World!")); err != nil {
log.Printf("Failed to write response: %v", err)
}
})

responseBody, err := json.Marshal(requestBody)
r.Get("/json", func(w http.ResponseWriter, r *http.Request) {
response := map[string]string{"message": "Hello, JSON!"}
responseBody, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
http.Error(w, "Failed to marshal JSON", http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "application/json")
w.Write(responseBody)
if _, err := w.Write(responseBody); err != nil {
log.Printf("Failed to write response: %v", err)
}
})

// Create a custom server with timeouts
server := &http.Server{
Addr: ":8080",
Handler: r,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 15 * time.Second,
}

// Start the server
if err := http.ListenAndServe(":8080", r); err != nil {
if err := server.ListenAndServe(); err != nil {
log.Fatalf("Failed to run server: %v", err)
}
}
9 changes: 9 additions & 0 deletions json.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,12 @@ func Unmarshal(data []byte, v interface{}) error {
}
return nil
}

// MapToKeyValuePairs converts a map to a slice of KeyValuePair
func MapToKeyValuePairs(m map[string]interface{}) []KeyValuePair {
pairs := make([]KeyValuePair, 0, len(m))
for k, v := range m {
pairs = append(pairs, KeyValuePair{Key: k, Value: v})
}
return pairs
}
Loading

0 comments on commit dfe0411

Please sign in to comment.