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

12 add api documentation #7

Open
wants to merge 87 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
87 commits
Select commit Hold shift + click to select a range
4d7a7dd
remove core limitation
matheuspolitano Dec 23, 2024
6c29e2f
fix main bugs
matheuspolitano Dec 24, 2024
1601264
fix main bugs
matheuspolitano Dec 24, 2024
1310b7b
down go version
matheuspolitano Dec 24, 2024
aa08816
add release file
matheuspolitano Dec 24, 2024
8e08e34
add release info in readme
matheuspolitano Dec 24, 2024
70f5b75
Merge pull request #1 from matheuspolitano/1-fix-main-bugs
matheuspolitano Dec 24, 2024
0982ac0
add new pipeline
matheuspolitano Dec 24, 2024
011b3a8
Merge pull request #2 from matheuspolitano/1-fix-main-bugs-1
matheuspolitano Dec 24, 2024
fee950d
fix pipeline
matheuspolitano Dec 24, 2024
6df7c14
Merge pull request #3 from matheuspolitano/1-fix-main-bugs-2
matheuspolitano Dec 24, 2024
3690243
Add new release file release_20241224104515.toml
github-actions[bot] Dec 24, 2024
4285907
improve the pipeline
matheuspolitano Dec 24, 2024
015183f
update release
matheuspolitano Dec 24, 2024
9a12574
Merge pull request #4 from matheuspolitano/2-improve-the-pipeline
matheuspolitano Dec 24, 2024
e8914ac
Add new release file release_20241224105329.toml
github-actions[bot] Dec 24, 2024
a363d78
pipeline adjust
matheuspolitano Dec 24, 2024
c9c86ad
Merge pull request #5 from matheuspolitano/3-remove-release-file
matheuspolitano Dec 24, 2024
d51f15e
Add new release file release_20241224111005.toml
github-actions[bot] Dec 24, 2024
d766a84
improve errors messages
matheuspolitano Dec 24, 2024
375a284
ädd local env and extras check in config
matheuspolitano Dec 24, 2024
a4e8ec9
change main go file
matheuspolitano Dec 24, 2024
497f3c8
add config
matheuspolitano Dec 24, 2024
4b0ed73
add config test
matheuspolitano Dec 24, 2024
e904542
run in sequence de config test and improve the config
matheuspolitano Dec 24, 2024
29e68c4
fix type error in port
matheuspolitano Dec 24, 2024
314338f
add note in release
matheuspolitano Dec 24, 2024
90991ca
improve task detail
matheuspolitano Dec 24, 2024
858c708
Merge pull request #6 from matheuspolitano/5-improve-config
matheuspolitano Dec 24, 2024
55ba43f
Add new release file release_20241224141902.toml
github-actions[bot] Dec 24, 2024
8a9556d
update readme
matheuspolitano Dec 24, 2024
049a9af
update readme
matheuspolitano Dec 24, 2024
0a5b0ce
update readme
matheuspolitano Dec 24, 2024
be3a5b7
update readme
matheuspolitano Dec 24, 2024
76b5c7f
add myduration
matheuspolitano Dec 25, 2024
6fc90b0
add test
matheuspolitano Dec 25, 2024
29092dc
add release
matheuspolitano Dec 25, 2024
ecb6071
Merge pull request #8 from matheuspolitano/7-improve-time-alive
matheuspolitano Dec 25, 2024
3e48f98
Add new release file release_20241225114904.toml
github-actions[bot] Dec 25, 2024
650acee
improve main.go and server start and shutdown
matheuspolitano Dec 25, 2024
dadf977
improve readme
matheuspolitano Dec 25, 2024
37eecea
Merge pull request #9 from matheuspolitano/6-improve-main.go
matheuspolitano Dec 25, 2024
81a767c
Add new release file release_20241225141728.toml
github-actions[bot] Dec 25, 2024
f6d55be
add env as type
matheuspolitano Dec 25, 2024
c99942f
add new pacakge and set new test
matheuspolitano Dec 25, 2024
d7b3d96
add production mod
matheuspolitano Dec 25, 2024
a94b47f
remove useless comments
matheuspolitano Dec 25, 2024
798ec5a
add max age
matheuspolitano Dec 25, 2024
e2dfaa5
improve response
matheuspolitano Dec 25, 2024
aa4a2f6
improve config and add new config
matheuspolitano Dec 25, 2024
1e16f01
update dockerimage
matheuspolitano Dec 25, 2024
4c3e893
add in readme
matheuspolitano Dec 25, 2024
2ad6d1f
add release
matheuspolitano Dec 25, 2024
aa6389b
update go version
matheuspolitano Dec 25, 2024
d355e9b
update pipeline and go version
matheuspolitano Dec 25, 2024
e1b534d
ignore scripts
matheuspolitano Dec 26, 2024
57f302b
improve release pipeline
matheuspolitano Dec 26, 2024
215b9c5
add ignore
matheuspolitano Dec 26, 2024
6a874e9
improve the validate release
matheuspolitano Dec 26, 2024
088cedf
improve release
matheuspolitano Dec 26, 2024
da84809
add response
matheuspolitano Dec 26, 2024
bdc9bbe
improve format
matheuspolitano Dec 26, 2024
49429e7
update release
matheuspolitano Dec 26, 2024
79b53c0
fix test
matheuspolitano Dec 26, 2024
c2db65b
Merge pull request #10 from matheuspolitano/7-improve-gin-api
matheuspolitano Dec 26, 2024
0b2c8a2
Add new release file release_20241226171013.toml
github-actions[bot] Dec 26, 2024
f203a84
improve memdb
matheuspolitano Dec 26, 2024
1cea555
Merge pull request #11 from matheuspolitano/8-improve-repository
matheuspolitano Dec 26, 2024
a8acdba
Add new release file release_20241226174317.toml
github-actions[bot] Dec 26, 2024
caa30ad
add docker
matheuspolitano Dec 26, 2024
69069d6
add release
matheuspolitano Dec 26, 2024
aad42e9
add release
matheuspolitano Dec 26, 2024
80eccc2
Merge pull request #12 from matheuspolitano/9-setup-docker
matheuspolitano Dec 27, 2024
c245e41
Release: Add release_20241227000208.toml
github-actions[bot] Dec 27, 2024
64c930a
cicd adjust
matheuspolitano Dec 27, 2024
ebc0cf5
Merge pull request #13 from matheuspolitano/10-migrate-deploy-file
matheuspolitano Dec 27, 2024
dedcac4
Release: Add release_20241227122723.toml
github-actions[bot] Dec 27, 2024
5166895
11 improve service #major (#14)
matheuspolitano Dec 27, 2024
06ac48a
Release: Add release_20241227124702.toml
github-actions[bot] Dec 27, 2024
cde0067
add doc
matheuspolitano Dec 27, 2024
e5c9e4b
improve readme
matheuspolitano Dec 27, 2024
9fa2a51
improve readme
matheuspolitano Dec 27, 2024
12d5bb3
improve readme
matheuspolitano Dec 27, 2024
10af987
improve readme
matheuspolitano Dec 27, 2024
89cbe2a
improve readme
matheuspolitano Dec 27, 2024
94d8b9a
add latest push in docker
matheuspolitano Dec 27, 2024
5704f8e
go mod tidy
matheuspolitano Dec 27, 2024
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
179 changes: 163 additions & 16 deletions .github/workflows/move-release.yml
Original file line number Diff line number Diff line change
@@ -1,54 +1,201 @@
name: Move release file into releases folder
name: Release and Tag Management

on:
push:
branches:
- main
workflow_dispatch:
inputs:
increment_type:
description: 'Version increment type'
required: false
default: 'patch'
type: choice
options:
- major
- minor
- patch

permissions:
contents: write

concurrency:
group: release-tag-${{ github.ref }}
cancel-in-progress: true

jobs:
move_release_file:
manage_release:
runs-on: ubuntu-latest

steps:
# 1. Check out the repository with full history to access tags
- name: Check out repository
uses: actions/checkout@v3
with:
persist-credentials: true # Allows push back to the repo
persist-credentials: true
fetch-depth: 0 # Fetch all history to access tags

- name: Set up environment variables (timestamp, file paths)
# 1.b Exit if commit is made by GitHub Actions bot
- name: Exit if commit is made by GitHub Actions bot
if: ${{ github.actor == 'github-actions[bot]' }}
run: |
echo "Commit made by GitHub Actions bot. Exiting workflow."
exit 0
# 1.a Capture the triggering commit message
- name: Capture triggering commit message
id: capture_commit
run: |
# Get the commit message of the event that triggered the workflow
if [ "${{ github.event_name }}" == "push" ]; then
COMMIT_MESSAGE=$(git log -1 ${{ github.sha }} --pretty=%B)
elif [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
COMMIT_MESSAGE=""
fi
echo "COMMIT_MESSAGE<<EOF" >> $GITHUB_ENV
echo "$COMMIT_MESSAGE" >> $GITHUB_ENV
echo "EOF" >> $GITHUB_ENV
# 2. Set up environment variables (timestamp, file paths)
- name: Set up environment variables
id: setvars
run: |
TIMESTAMP=$(date +'%Y%m%d%H%M%S')
echo "TIMESTAMP=$TIMESTAMP" >> $GITHUB_ENV
echo "RELEASE_SOURCE_FILE=release.toml" >> $GITHUB_ENV
echo "RELEASE_FOLDER=releases" >> $GITHUB_ENV
echo "RELEASE_TARGET_FILE=release_${TIMESTAMP}.toml" >> $GITHUB_ENV

- name: Move file to releases folder
# 3. Move the release file to the releases folder
- name: Move release file
run: |
echo "Using TIMESTAMP=$TIMESTAMP"
echo "Copying $RELEASE_SOURCE_FILE to $RELEASE_FOLDER/$RELEASE_TARGET_FILE"
echo "Moving $RELEASE_SOURCE_FILE to $RELEASE_FOLDER/$RELEASE_TARGET_FILE"
mkdir -p "$RELEASE_FOLDER"
mv "$RELEASE_SOURCE_FILE" "$RELEASE_FOLDER/$RELEASE_TARGET_FILE"

- name: Commit and push changes
# 4. Commit and push the changes
- name: Commit changes
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"

# Remove old file from Git (if it was already tracked)
# Remove old release file from tracking
git rm --cached "$RELEASE_SOURCE_FILE" || true


git add "$RELEASE_FOLDER/$RELEASE_TARGET_FILE"

git commit -m "Add new release file $RELEASE_TARGET_FILE"
git commit -m "Release: Add $RELEASE_TARGET_FILE"
git push
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# So we can use $TIMESTAMP, $RELEASE_FOLDER, and $RELEASE_TARGET_FILE again
TIMESTAMP: ${{ env.TIMESTAMP }}
RELEASE_FOLDER: ${{ env.RELEASE_FOLDER }}
RELEASE_TARGET_FILE: ${{ env.RELEASE_TARGET_FILE }}

# 5. Get the latest tag
- name: Get latest tag
id: get_latest_tag
run: |
LATEST_TAG=$(git describe --tags `git rev-list --tags --max-count=1` || echo "")
echo "LATEST_TAG=${LATEST_TAG}" >> $GITHUB_OUTPUT
# 6. Validate the latest tag format
- name: Validate latest tag
if: steps.get_latest_tag.outputs.LATEST_TAG != ''
run: |
echo "${{ steps.get_latest_tag.outputs.LATEST_TAG }}" | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' || { echo "Invalid tag format"; exit 1; }
# 7. Determine version increment
- name: Determine version increment
id: version_type
run: |
# If workflow_dispatch input is provided, use it; otherwise, use the captured commit message
if [ "${{ github.event_name }}" == "workflow_dispatch" ] && [ -n "${{ github.event.inputs.increment_type }}" ]; then
INCREMENT="${{ github.event.inputs.increment_type }}"
else
# Use the captured commit message to determine increment
if echo "$COMMIT_MESSAGE" | grep -q '#major'; then
INCREMENT="major"
elif echo "$COMMIT_MESSAGE" | grep -q '#minor'; then
INCREMENT="minor"
else
INCREMENT="patch"
fi
fi
echo "INCREMENT=${INCREMENT}" >> $GITHUB_ENV
env:
COMMIT_MESSAGE: ${{ env.COMMIT_MESSAGE }}

# 8. Extract the current version number without the 'v' prefix
- name: Extract version number
id: extract_version
run: |
if [ -z "${{ steps.get_latest_tag.outputs.LATEST_TAG }}" ]; then
VERSION_NUMBER="0.0.0"
else
VERSION_TAG="${{ steps.get_latest_tag.outputs.LATEST_TAG }}"
VERSION_NUMBER="${VERSION_TAG#v}"
fi
echo "VERSION_NUMBER=${VERSION_NUMBER}" >> $GITHUB_ENV
# 9. Increment the version based on the determined type
- name: Increment version
id: increment_version
run: |
IFS='.' read -r MAJOR MINOR PATCH <<< "$VERSION_NUMBER"
case "${INCREMENT}" in
major)
NEW_VERSION="v$((MAJOR + 1)).0.0"
;;
minor)
NEW_VERSION="v$MAJOR.$((MINOR + 1)).0"
;;
patch)
NEW_VERSION="v$MAJOR.$MINOR.$((PATCH + 1))"
;;
*)
echo "Unknown increment type: ${INCREMENT}"
exit 1
;;
esac
echo "NEW_VERSION=${NEW_VERSION}" >> $GITHUB_ENV
# 10. Create and push the new tag
- name: Create and push tag
run: |
git tag -a "${NEW_VERSION}" -m "Release ${NEW_VERSION}: Move release file into releases folder"
git push origin "${NEW_VERSION}"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NEW_VERSION: ${{ env.NEW_VERSION }}

# 11. Build and push Docker image to Docker Hub
- name: Log in to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}

- name: Build and push Docker image
uses: docker/build-push-action@v3
with:
context: .
push: true
tags: matheuspolitano/couponservice:${{ env.NEW_VERSION }}

# 12. Create GitHub Release for the new tag
- name: Create GitHub Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ env.NEW_VERSION }}
release_name: Release ${{ env.NEW_VERSION }}
body: |
## Changes
- Move release file into releases folder.
- Docker image updated to version `${{ env.NEW_VERSION }}`.
draft: false
prerelease: false

# 13. Upload the release file as an asset to the GitHub Release
- name: Upload Release Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./${{ env.RELEASE_FOLDER }}/${{ env.RELEASE_TARGET_FILE }}
asset_name: ${{ env.RELEASE_TARGET_FILE }}
asset_content_type: application/octet-stream
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ FROM alpine:3.19
WORKDIR /app
COPY --from=builder /app/main .


EXPOSE 8080 9090
ENV API_PORT=80
EXPOSE 80
CMD [ "/app/main" ]

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Configure the application using environment variables with support for a `.env`
- **`API_ALLOW_ORIGINS`**
- **Explanation:** Allow origins by CORS. Is valid only is production environment
- **Format:** Specify the hostname divide by split `https://example.com,https://api.example.com`
- **Default:** List of empty
- **Default:** Allow all origins

### `.env` File

Expand Down
13 changes: 7 additions & 6 deletions cmd/coupon_service/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,16 @@ func main() {
serverErrors := make(chan error, 1)

go func() {
log.Printf("Starting Coupon service server on port %s", cfg.API.Port)
log.Printf("Starting Coupon service server on port %s", cfg.API.PORT)
serverErrors <- server.Start()
}()

quit := make(chan os.Signal, 1)
signal.Notify(quit, interruptSignals...)

waitForShutdown(serverErrors, quit, cfg.API.Time_Alive.ParseTimeDuration())
waitForShutdown(serverErrors, quit, cfg.API.TIME_ALIVE.ParseTimeDuration())

ctx, cancel := context.WithTimeout(context.Background(), cfg.API.Shutdown_Timeout.ParseTimeDuration())
ctx, cancel := context.WithTimeout(context.Background(), cfg.API.SHUTDOWN_TIMEOUT.ParseTimeDuration())
defer cancel()

if err := server.Shutdown(ctx); err != nil {
Expand All @@ -54,14 +54,15 @@ func main() {

}

func waitForShutdown(serverErrors <-chan error, quit <-chan os.Signal, Time_Alive time.Duration) {
if Time_Alive > 0 {
func waitForShutdown(serverErrors <-chan error, quit <-chan os.Signal, TIME_ALIVE time.Duration) {
if TIME_ALIVE > 0 {
log.Printf("Server alive until %v", time.Now().Add(TIME_ALIVE))
select {
case err := <-serverErrors:
log.Panicf("Could not start server: %v", err)
case sig := <-quit:
log.Printf("Received signal %s. Initiating graceful shutdown...", sig)
case <-time.After(Time_Alive):
case <-time.After(TIME_ALIVE):
log.Printf("Timeout reached. Initiating graceful shutdown...")
}
} else {
Expand Down
12 changes: 12 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
version: '3.9'
services:
coupon_service:
build:
context: '.'
dockerfile: Dockerfile
environment:
- API_PORT=80
- API_ENV=production
- API_TIME_ALIVE=10s
ports:
- 8082:80
30 changes: 15 additions & 15 deletions internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,25 +23,25 @@ type Service interface {
// Config store main api settings
// *Fields are with camel case to be read by the godotenv
type Config struct {
Port string `env:"API_PORT"`
Env mytypes.Environment `env:"API_ENV"`
Time_Alive mytypes.MyDuration `env:"API_TIME_ALIVE"`
Shutdown_Timeout mytypes.MyDuration `env:"API_SHUTDOWN_TIMEOUT"`
Allow_Origins mytypes.AllowOrigins `env:"API_ALLOW_ORIGINS"`
PORT string `env:"API_PORT"`
ENV mytypes.Environment `env:"API_ENV"`
TIME_ALIVE mytypes.MyDuration `env:"API_TIME_ALIVE"`
SHUTDOWN_TIMEOUT mytypes.MyDuration `env:"API_SHUTDOWN_TIMEOUT"`
ALLOW_ORIGINS mytypes.AllowOrigins `env:"API_ALLOW_ORIGINS"`
}

type API struct {
srv *http.Server
MUX *gin.Engine
mux *gin.Engine
svc Service
CFG Config
cfg Config
}

func New[T Service](cfg Config, svc T) (*API, error) {
var logger *zap.Logger
var err error

if cfg.Env == mytypes.Production {
if cfg.ENV == mytypes.Production {
log.Println("Running in production mode")
gin.SetMode(gin.ReleaseMode)

Expand All @@ -61,8 +61,8 @@ func New[T Service](cfg Config, svc T) (*API, error) {

r := initializeGinEngine(cfg, logger)
api := &API{
MUX: r,
CFG: cfg,
mux: r,
cfg: cfg,
svc: svc,
}
return api.withServer().withRoutes(), nil
Expand All @@ -71,11 +71,11 @@ func New[T Service](cfg Config, svc T) (*API, error) {
func initializeGinEngine(cfg Config, logger *zap.Logger) *gin.Engine {
var router *gin.Engine

if cfg.Env == mytypes.Production {
if cfg.ENV == mytypes.Production {
router = gin.New()
router.Use(ginLogger(logger), gin.Recovery())
router.Use(cors.New(cors.Config{
AllowOrigins: cfg.Allow_Origins,
AllowOrigins: cfg.ALLOW_ORIGINS,
AllowMethods: []string{"GET", "POST", "PUT", "DELETE"},
AllowHeaders: []string{"Origin", "Content-Type", "Authorization"},
AllowCredentials: true,
Expand Down Expand Up @@ -119,8 +119,8 @@ func ginLogger(logger *zap.Logger) gin.HandlerFunc {

func (a *API) withServer() *API {
a.srv = &http.Server{
Addr: fmt.Sprintf(":%s", a.CFG.Port),
Handler: a.MUX,
Addr: fmt.Sprintf(":%s", a.cfg.PORT),
Handler: a.mux,
ReadHeaderTimeout: time.Duration(5) * time.Second,
ReadTimeout: time.Duration(10) * time.Second,
WriteTimeout: time.Duration(5) * time.Second,
Expand All @@ -130,7 +130,7 @@ func (a *API) withServer() *API {
}

func (a *API) withRoutes() *API {
apiGroup := a.MUX.Group("/api")
apiGroup := a.mux.Group("/api")
apiGroup.POST("/apply", a.Apply)
apiGroup.POST("/create", a.Create)
apiGroup.GET("/coupons", a.Get)
Expand Down
2 changes: 1 addition & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func New(envFilePath string, opts ...OptionsConfigFunc) (Config, error) {
return cfg, fmt.Errorf("failed to load config: %w", err)
}

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

Expand Down
Loading