
Example CRUD project applying Hexagonal Architecture, Domain-Driven Design (DDD), Event-Driven Architecture (EDA), Command Query Responsibility Segregation (CQRS), Behavior-Driven Development (BDD), Continuous Integration (CI), and more… in Go.
Showcase
CLI
Run (Demo)
go run github.com/bastean/codexgo/v4/cmd/codexgo@latest -demo
- Demo version does not require any configuration, because the required ENV values are already preset.
- Here we can find the ENV preset values that are used in the Demo.
In-Memory implementation will be used for EventBus, CommandBus, QueryBus and Database (BadgerDB).
- Links to confirm and recover the account are sent through the
Terminal with the following messages:
- “Hi <username>, please confirm your account through this link: <link>”.
- “Hi <username>, please reset your password through this link: <link>”.
Installation
go install github.com/bastean/codexgo/v4/cmd/codexgo@latest
codexgo -h
_________ ________________
_____________ ______ /_____ ____ __ __ ____/__ __ \
_ ___/_ __ \_ __ / _ _ \__ |/_/ _ / __ _ / / /
/ /__ / /_/ // /_/ / / __/__> < / /_/ / / /_/ /
\___/ \____/ \__,_/ \___/ /_/|_| \____/ \____/ v4.17.4
Example CRUD project applying Hexagonal Architecture, DDD, EDA, CQRS, BDD, CI, and more... in Go.
Usage: codexgo [flags]
-demo
Use preset ENV values
-env string
Path to custom ENV file
-v Print version
Usage
- We can use the .env.demo.cli file or we can create our own
.env file where we define our own values.
- In the .env.example.cli file, we can see the values that can be used.
- If
CODEXGO_SMTP_* is omitted, the links to confirm and recover the account are sent through the Terminal with the following messages:
- “Hi <username>, please confirm your account through this link: <link>”.
- “Hi <username>, please reset your password through this link: <link>”.
- We can define our own SMTP configuration by simply modifying the
CODEXGO_SMTP_* variables, then we will be able to receive the links by mail.
- If
CODEXGO_BROKER_* is omitted, an in-memory EventBus will be used.
In-Memory implementation will be used for CommandBus and QueryBus.
- If
CODEXGO_DATABASE_* is omitted, a BadgerDB in-memory database will be used.
- We can use a file as a database instead of memory by defining the file name in the
CODEXGO_DATABASE_BADGERDB_DSN variable.
codexgo -env path/to/.env
Docker
Run (Demo)
- System Requirements
- In the Demo version (.env.demo):
RabbitMQ implementation will be used for the EventBus.
- URL:
http://localhost:15672
- User/Password:
codexgo-demo
In-Memory implementation will be used for CommandBus and QueryBus.
MongoDB implementation will be used as Database.
- Compass:
mongodb://codexgo-demo:codexgo-demo@localhost:27017
Mailpit will be used as SMTP to receive emails with the links to confirm and recover the account.
- URL:
http://localhost:8025
codexGO Server.
- URL:
http://localhost:8080
task demo
Features
Project Layout
Git
- Hooks managed by husky:
- Commit message helper using czg.
- Interactive prompt that allows you to write commits following the Conventional Commits rules:
task commit
Scanners
Debuggers
Tests
Releases
GitHub
- Actions for:
- Setup Languages and Dependencies (setup)
- Workflows running:
- Automatically (Triggered by Push or Pull requests) (ci):
- Secrets
- Vulnerabilities
- Misconfigurations
- Linting
- Testing
- Manually (Using the Actions tab on GitHub):
- Issue Templates (Defaults).
Devcontainer
- Multiple Features already pre-configured:
- Go
- Task
- Docker in Docker
- Light-weight Desktop (Fluxbox)
- SSH
- Extensions and their respective settings to work with:
- Go
- Task
- Docker
- MongoDB
- Postman
- templ
- Cucumber
- YAML
- TOML
- Prettier
- Better Comments
- Comment Divider
- Todo Tree
- cSpell
- Fomantic Snippets
Docker
- Dockerfile
- Multi-stage builds:
- Development
- Testing
- Build
- Production
- Compose
- Switched by ENVs and Profiles.
Broker
Server
Security
- Server log files.
- Requests Rate Limiting.
- Data authentication via JWT managed by Session Cookies.
- Captcha implementation in forms.
- Form validation at the client using Fomantic - Form Validation.
- On the server, the validations are performed using the Value Objects defined in the Context.
- Account confirmation and recovery via Mail or Terminal.
- Limited to a certain number of attempts in a given time interval.
- Password hashing using Bcrypt.
- cDeps
- Copies the files required by the browser dependencies from the node_modules folder and places them inside the static folder on the server.
- syncENV
- Synchronize all .env* files in the directory using an .env model.
Scripts
- run
- Display the logs and redirect them to a file whose name depends on the time at which the service was run.
- Used in Production Image.
Domain > (Infrastructure | Application) > Presentation
Bounded Context (App/Business/Department) > Modules (Troubleshooting) > Layers (Domain, Infrastructure & Application)
- Domain (Logic Core)
- Value Objects (Entities)
- Mother Creators
- Unit Tests
- Messages
- Aggregates (Sets of Entities)
- Aggregate Root (Core Set)
- Mother Creators
- Role Interfaces (Ports)
- Model Interfaces
- Use Cases
- Handlers/Consumers
- Services (Abstract Logic)
- Errors (Management)
- Infrastructure (Port Adapters)
- Persistence
- Repository Mocks
- Implementations (Adapters)
- Integration Tests
- Communication
- Broker Mocks
- Implementations (Adapters)
- Integration Tests
- Application (Orchestration of Domain Logic)
- Use Cases
- Commands
- Queries/Responses
- Handlers/Consumers
- Implementations
- Unit Tests
Services > App > (Presentation)
- Presentation (Consumers of Bounded Context Modules)
- Services (Mapping)
- Centralize Imports
- Initializations
- Server
- Templates
- Handlers
- Routes
- Features (Gherkin)
Workflow
Idea
The system allows users to register a new account, log in and update their data or permanently delete their account, as well as verify and reset their account through a link sent to their email.
Functionality
It is a monolith where CRUD operations can be performed from different presentations to the same database, this allows us to manage users from the different presentations available, in addition to having a messaging system that allows to communicate the events occurred, thus avoiding a coupling to the source of the same.
Folders
-
pkg/context/(modules)
- It is the logical core that contains all the necessary functionalities that are agnostic of any presentation.
-
internal/pkg/service
- It is responsible for initializing all context functionalities so that they are ready for use, as well as for “mapping” certain values to centralize all imports required for presentations in a single place.
-
internal/app/(presentations)
- These applications will be used as presentations in order to serve the functionalities to an end user.
Idiomatic
VSCode Snippets available (We can see them in IntelliSense (Ctrl+Space) or simply by typing go-).
- Domain
errors.New[...](), errors.BubbleUp() & errors.Panic()
- Only in the
Domain layer and in the *_test.go files can we throw errors.Panic().
- Infrastructure
New*(), Open() & Close()
errors.New[...]() & errors.BubbleUp()
- Application
Run(), Handle() & On()
errors.New[...]() & errors.BubbleUp()
- Presentation
- Modules
Start() & Stop()
errors.BubbleUp()
- Services / Apps
Init(), Up() & Down()
errors.New[...]() & errors.BubbleUp()
- In
Apps we will handle Bubble Errors.
- Main
log.Fatal() & log.[Wrap]()
- Only
main() can use log.Fatal().
- Logs
[embed]
- We use
[] to “embed” external values such as error messages, fields, etc… inside our messages.
- ENVs
os.[Getenv/LookupEnv]()
- Only handle
ENVs directly in the Presentation layer and in the *_test.go files.
- At the
Infrastructure layer, ENVs are received via arguments through function parameters.
- Blocks
const, var, & type
- We will group only those that are declared on a single line.
- Tests
- Subject/System/State Under Test (SUT)
- The
SUT will only be explicitly defined within the “suite (in the s.SUT field)” in those tests that cover several entities, such as “handlers/consumers, use cases, roles…”.
- When testing only “functions and/or methods”, it is not necessary to define an explicit
SUT within the “suite (in the s.SUT field)”, since the name of the “test cases” will indicate which SUT that specific case belongs to.
- Suite
<SUT>TestSuite
- The name of the
<SUT> can be that of the package, function, or type.
<SUT>Suite
- When shared to test different implementations of the same
interface.
- Cases
- Happy Path
Test<Function/Method>()
Test<Function/Method><With/Without>*()
- Corner Case
Test<Function/Method><Err/Panic>*
- The semantics of the message and/or the words used after
<Err/Panic> should only come from the error that is checked in the “test case”.
- We will only check for errors originating in the function or method being tested.
- With “Generic[…] Functions”.
Test<Function>*()
Test<Function>*<With/Without>*()
Test<Function>*<Err/Panic>*()
- Sentinel
- They are used to “compare” already defined values against “hardcoded” values to ensure their integrity.
- Exceptions
- In the “errors” package, there may be exceptions in the names of the “test cases” to avoid confusion.
- Mothers
- Subject Under Test (SUT)
- The
SUT always refers to the “value (subject)” used within the method, whether to return an instance or generate an error.
- Factory
- Valid (used in “Happy paths”)
- Invalid (used in “Corner Cases”)
- When it is necessary to define parameters in the method we use
With to describe them, but With is not necessary in methods with a single “…variadic parameter”.
<SUT>ValidWith*()
<SUT>InvalidWith*()
- Wrap
- These methods are only used to avoid handling error comparisons in “test cases”.
<SUT>New()
<SUT>Copy()
<SUT>Replace()
- With the exception of
Invalid, all other methods that generate an error must throw a panic() and should never be ignored using _.
- There will only be one
Mother (mother.go) per package.
Snippets
- Check
- Spelling
- Format
- Jumps
- Test
…v0 > dev0.1.0 > ci/dev0.1.0 > main > v0…
Create v0 branch from main.
task git-v0
Create development branch dev0.1.0 from v0.
task git-dev0.1.0
Create branch ci/dev0.1.0 from dev0.1.0 to ensure that the workflows run correctly with the new changes before merging them with main.
task git-ci/dev0.1.0
Once the workflows have been successfully passed, the new changes from ci/dev0.1.0 will be merged into main.
task git-main-ci/dev0.1.0
After releasing the new version v0.1.0, the main and v0 branches in our local repository will be updated.
task git-pull-v0
To end the cycle, the dev0.1.0 and ci/dev0.1.0 branches will be deleted.
task git-cleanup-dev0.1.0
First Steps
Clone
HTTPS
git clone https://github.com/bastean/codexgo.git && cd codexgo
SSH
git clone [email protected]:bastean/codexgo.git && cd codexgo
Initialize
Dev Container (Recommended)
-
System Requirements
-
Start VS Code
code .
-
Open Command Palette
-
Run
Dev Containers: Reopen in Container
-
SSH (Optional)
- We can connect to our
Dev Container via SSH in the following ways:
-
If we have Task installed on our host, being in the root of the repository
task connect-2222/vscode@localhost
-
Using the SSH Client of our host
ssh -p 2222 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o GlobalKnownHostsFile=/dev/null vscode@localhost
-
Password: vscode
-
Desktop (Optional)
- We can connect to our
Dev Container via VNC using our web browser.
Locally
-
System Requirements
-
Run
task init
ZIP
curl -sSfLO https://github.com/bastean/codexgo/archive/refs/heads/main.zip \
&& unzip main.zip \
&& mv codexgo-main <repository> \
&& rm main.zip \
&& cd <repository> \
&& task genesis \
&& git commit -m "feat(genesis): codexgo" \
&& git branch -M main \
&& git remote add github https://github.com/<user>/<repository>.git \
&& git push -u github main \
&& git status
Repository initialization from ZIP (Optional)
Design
favicon-512.png (512x512)
Screenshots
desktop.png (1536x860)
mobile.png (425x800)
Readme
Mocks
Repository
We can use VSCode Search & Replace (Ctrl+Shift+F) with the following options enabled:
- Match Case (
Alt+C)
- Match Whole Word (
Atl+W)
Genesis
GitHub
Settings
Actions
- Workflows
- Release
- Run workflow
- Use workflow from
- Status
- Bump
- Pre-release
GitHub Actions (Optional)
By default, the user used to create commits and tags in workflows is github-actions[bot], whose creations are not signed. If we want the creation of commits and tags to be signed, we must create the specified “Repository Secrets”, this way by selecting GPG Sign when manually launching a workflow everything will be created using the information obtained from the “GPG Key”.
Settings tab
Secrets and variables
Run
ENVs
If we want to modify the values inside some .env file, here .env.example.demo we can see the values that can be used.
RabbitMQ
- URL:
http://localhost:15672
- User/Password:
codexgo-dev
MongoDB
- Compass:
mongodb://codexgo-dev:codexgo-dev@localhost:27017
Mailpit
- URL:
http://localhost:8025
codexGO Server
- URL:
http://localhost:8080
codexGO Live-Reloading Server
- URL:
http://localhost:8090
task compose-dev
Tests
Unit
task test-unit
task test-flaky
task compose-test-integration
task compose-test-acceptance
Unit / Integration / Acceptance (.env.demo.test)
task compose-tests
- We must define our own SMTP configuration in the
CODEXGO_SMTP_* variables, to receive the links by mail.
- By default, as there are no values set, the links will be sent through the terminal.
RabbitMQ
- URL:
http://localhost:15672
- User/Password:
codexgo
MongoDB
- Compass:
mongodb://codexgo:codexgo@localhost:27017
codexGO Server
- URL:
http://localhost:8080
task compose-prod
Tech Stack
Base
Please see
Contributing
Contributions and Feedback are always welcome!
License
MIT
评论