Initial commit.
This commit is contained in:
13 files changed
+711
No files matched your search
@@ -0,0 +1,34 @@
|
||||
# Coding Standards
|
||||
|
||||
Этот репозиторий содержит стандарты кодирования, которые я применяю в своих проектах. Они добавляются в репозиторий как подмодуль git.
|
||||
|
||||
При какой-либо работе с проектами, где содержатся эти стандарты кодирования, следовать им неукоснительно и полноценно **обязательно**.
|
||||
|
||||
Для облегчения работы нейронок (а по большей части именно для них эти стандарты и пишутся) основной текст стандартов написан на английском языке.
|
||||
|
||||
- [Basic project structure](project_structure.md)
|
||||
|
||||
Более подробное описание блоков:
|
||||
|
||||
- [Application](components/application.md).
|
||||
- [Domains](components/domains.md).
|
||||
- [Clients](components/clients.md).
|
||||
- [DTO and Models](components/dtos-models.md).
|
||||
- [Storages](components/storages.md).
|
||||
- [Deliveries](components/deliveries.md).
|
||||
- [Middlewares](components/middlewares.md).
|
||||
- [Errors](components/errors.md)
|
||||
|
||||
Прочее:
|
||||
|
||||
- [Logging](components/logging.md).
|
||||
- [Testing and linting](components/testing_and_linting.md).
|
||||
- [CI/CD](components/cicd.md).
|
||||
|
||||
Нейронкам - не забудь прочитать `AGENTS.md` из корня исходного репозитория для получения указаний по конкретному проекту.
|
||||
|
||||
## Лицензия
|
||||
|
||||
WTFPL: Do What The Fuck You Want To Public License.
|
||||
|
||||
Иначе - пользуйтесь, как хотите.
|
||||
@@ -0,0 +1,63 @@
|
||||
# Application singleton
|
||||
|
||||
This is a structure that controls the whole application's lifecycle:
|
||||
|
||||
- Startup (in `Start() error` function).
|
||||
- Shutdown (in `Shutdown() []error` function).
|
||||
- Domains registry (`[]Domain`).
|
||||
- Base logger (see [Logging](logging.md)).
|
||||
|
||||
This structure is passed to all parts of application - domains, storages, clients to external services and so on, for re-using domains, global context, logger and other parts.
|
||||
|
||||
## Structure initialization
|
||||
|
||||
Structure initialization for that singleton should be done with `New()` without returning any error, as it will initialize internal state and nothing else. It consists of:
|
||||
|
||||
- Global `context.Context` creation to use (with `Context() context.Context` function for retrieving that context).
|
||||
- Internal storage creation for domains registry.
|
||||
- Base logger creation (see [Logging](logging.md)).
|
||||
|
||||
## App startup and shutdown
|
||||
|
||||
Application's startup and shutdown are done in `Start() error` and `Shutdown() []error` functions respectively.
|
||||
|
||||
Startup function sequentially runs these functions for every registered domain, each function in a separate iteration:
|
||||
|
||||
- `ConnectDependencies() error`.
|
||||
- `Configure() error`.
|
||||
- `LaunchStartupTasks() error`.
|
||||
|
||||
It should return a wrapped error if anything goes wrong here.
|
||||
|
||||
As startup function calls domain functions in iterations, you should put domains initialization in `main()` function in proper order - if some domain requires configuration of another domain, it should be placed after that domain.
|
||||
|
||||
Shutdown function is different as it should run `Shutdown() error` on every registered domain, add every returned error to `[]error` and return that slice. Domains order is reversed compared to `Start()` function.
|
||||
|
||||
Singleton provides `ShutdownChan()` function that returns a channel to which a signal will be sent when SIGTERM is received.
|
||||
|
||||
## Domains registry
|
||||
|
||||
Simple `[]Domain` field in Application structure. Two functions should be present:
|
||||
|
||||
- `RegisterDomain(domain Domain) error` which registers domain by adding it in `[]Domain` or returns error if domain with such name is already registered.
|
||||
- `Domain(name string) Domain` which returns domain by name or nil if domain isn't registered.
|
||||
|
||||
Also domains registry field should be secured with `sync.RWMutex` so every part of application can safely retrieve any required dependency on any stage.
|
||||
|
||||
### Registering a domain
|
||||
|
||||
Domain's registration should happen with `RegisterDomain(domain Domain) error` function:
|
||||
|
||||
- Checks if domain with same name (obtained via `Name() string` interface's function) is already registered. If so - returns an error.
|
||||
- Registers domain with registry by adding it to `[]Domain`.
|
||||
- Runs `Initialize() error` function from domain and returns wrapped error if initialization function returned it.
|
||||
|
||||
### Retrieving a domain
|
||||
|
||||
Domain retrieval should be done via `Domain(name string) Domain` function in a proper domain's `ConnectDependencies() error` function.
|
||||
|
||||
If requested domain is not registered, that function should return nil and domain that requested unknown domain should return an `ErrDomainUnknown` error from `application` package.
|
||||
|
||||
## Logging
|
||||
|
||||
Comprehensive logging documentation can be found in [Logging](logging.md).
|
||||
@@ -0,0 +1,5 @@
|
||||
# CI/CD
|
||||
|
||||
Every project that is using these coding standards should also use a CI/CD system. Name of CI/CD system should be present somewhere in project's documentation/ADRs and CI/CD should always do linting and testing steps.
|
||||
|
||||
When selecting base image for linting and tests, it is important to have full understanding of project's dependencies as some of them might require third-party C headers and C compiler (and maybe other compilers).
|
||||
@@ -0,0 +1,34 @@
|
||||
# Clients
|
||||
|
||||
Clients are Go packages that provide easy access to application's API or external API. Hence, this document describes two types of clients:
|
||||
|
||||
- **Own client**.
|
||||
- **External API client**.
|
||||
|
||||
## Own client
|
||||
|
||||
Own client is a client to application's own network API that is accessible through domain's deliveries (see [Deliveries](deliveries.md)). It should conform to this set of rules:
|
||||
|
||||
- Be placed in `client` package in project's root directory.
|
||||
- Be configurable with functional options.
|
||||
- NOT expose low-level API (e.g. ability to configure HTTP client by assigning parameters directly to its fields).
|
||||
- Have `schema` package in it with API contract's data schema.
|
||||
- Have proper and comprehensive comments on exported functions, structures and their fields.
|
||||
- Public (exported) functions should return schema structure and error or just error if no data is returned.
|
||||
- Validate request's data before launching network communication.
|
||||
|
||||
Own client should be explicitly mentioned in ADRs (Architecture Decision Records) or any other document that describes application's functionality. If own client isn't mentioned there - it should not be implemented.
|
||||
|
||||
Also, own client should not receive `*application.Application` as it won't be on end-user side. For lifecycle-related things it should receive `context.Context` via configuration.
|
||||
|
||||
### API contract schema
|
||||
|
||||
All data that goes via own client should be wrapped in a structure that lies in `schema` package within client for extensibility and maintainability.
|
||||
|
||||
Every schema structure should have `Validate() error` function that validates request's data early, before it goes to API.
|
||||
|
||||
## External API client
|
||||
|
||||
External API client is a client to externally hosted application. It should conform to the same rules as own client with these exceptions:
|
||||
|
||||
- Client should be placed in `client` directory of domain (see [Domains](domains.md)) and should not be within "core" or "features" domains.
|
||||
@@ -0,0 +1,45 @@
|
||||
# Deliveries
|
||||
|
||||
Deliveries are a concept of clean architecture that is responsible for network API interaction. It consists of:
|
||||
|
||||
- Handling structure.
|
||||
- Interface that describes API requirements for domain's service structure.
|
||||
|
||||
Deliveries should be placed in `delivery/DELIVERY_TYPE` directory within domain, like `internal/domains/core/config/delivery/http_external` for configuration-related HTTP API that is accessible to external clients.
|
||||
|
||||
## Handling structure
|
||||
|
||||
Delivery's handling structure is similar to domain's one:
|
||||
|
||||
- It initializes with `Initialize(app *application.Application, dmn domain) error` function.
|
||||
- It should have own logger (see [Logging](logging.md)).
|
||||
- It should not be exported (private structure).
|
||||
|
||||
And that's it:
|
||||
|
||||
- It SHOULD NOT register itself with Application singleton as domain.
|
||||
- It CANNOT have or use storages.
|
||||
- It CANNOT have models or DTOs, delivery should re-use domain's models.
|
||||
- If application's client isn't present - API data structure should be in same file with handler function and unexported.
|
||||
- It SHOULD NOT conform to Domain interface (e.g. `Configure()`, `ConnectDependencies()` and other interface's functions shouldn't be present).
|
||||
- It should use only own domain and CANNOT use others.
|
||||
- With notable exception of HTTP server's handlers registration.
|
||||
- It should specify own domain contract as unexported interface named `domain` in same-named file.
|
||||
|
||||
Yet it should receive `*application.Application` on initialization like a regular domain to obtain logger.
|
||||
|
||||
Domain itself should be passed to delivery as second parameter and initializer should receive it as own domain's service interface (see below).
|
||||
|
||||
## API handlers
|
||||
|
||||
API handlers registration should happen in `(h *handler) registerHandlers() error` function.
|
||||
|
||||
## Domain's service interface
|
||||
|
||||
Delivery should have own domain interface that is different from inter-domain API and is described in `domain.go` file in delivery's package.
|
||||
|
||||
## Models, schemas
|
||||
|
||||
As delivery is actually a part of domain, working internally with domain's models is allowed, but responses should always use different structures (delivery schemas or application's client schemas).
|
||||
|
||||
Delivery schemas are request and response structures that are placed in same file with request handling function. They should be unexported so they do not pollute IDE's autocompletion.
|
||||
@@ -0,0 +1,134 @@
|
||||
# Domains
|
||||
|
||||
All domains must conform to the generic domain interface located in `internal/application`:
|
||||
|
||||
```go
|
||||
type Domain interface{
|
||||
// Configure performs domain configuration. Called after ConnectDependencies().
|
||||
Configure() error
|
||||
// ConnectDependencies gets necessary dependencies (other domains) from application singleton's
|
||||
// registry. Called on application start after all needed domains are registered with singleton.
|
||||
ConnectDependencies() error
|
||||
// Initialize initializes internal state. Called when RegisterDomain() is issued.
|
||||
Initialize() error
|
||||
// LaunchStartupTasks launches tasks that should perform some actions on start or when these tasks
|
||||
// should work in background (in separate goroutine). Called after ConnectDependencies() and Configure().
|
||||
LaunchStartupTasks() error
|
||||
// Name returns domain name.
|
||||
Name() string
|
||||
// Shutdown performs shutdown actions for domain.
|
||||
Shutdown() error
|
||||
}
|
||||
```
|
||||
|
||||
## Domains categories
|
||||
|
||||
Every domain MUST have proper categorisation. Currently this document defines some standard categories:
|
||||
|
||||
- `core` - core/low-level functionality (e.g. HTTP server, database connection handling, low-level local disk storage handling).
|
||||
- `features` - business code itself (e.g. working with users).
|
||||
- `integrations` - third-party integrations proxy domains (e.g. integration with third-party API).
|
||||
|
||||
This isn't a comprehensive list, as specific application might require own domain category not described here, for example, `protocols` category where chat protocols lie (for a multi-protocol messaging app).
|
||||
|
||||
## Domains registration
|
||||
|
||||
Domains should register themselves in `Initialize(app *application.Application) error` function which should be called in `main()` function of binary. It should be done like that:
|
||||
|
||||
in main.go:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import "log/slog"
|
||||
|
||||
func main() {
|
||||
app := application.New()
|
||||
|
||||
lgr := app.Logger("module", "main")
|
||||
|
||||
checkError(lgr, somedomain.Initialize(app))
|
||||
|
||||
checkError(lgr, app.Start())
|
||||
|
||||
<-app.ShutdownChan
|
||||
|
||||
if errs := app.Shutdown(); errs != nil {
|
||||
lgr.Error("Failed to shutdown app!", "errors", errs)
|
||||
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
|
||||
func checkError(lgr *slog.Logger, err error) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
lgr.Error("Failed to start app!", "error", err.Error())
|
||||
|
||||
//revive:disable-next-line:deep-exit
|
||||
os.Exit(1)
|
||||
}
|
||||
```
|
||||
|
||||
in `internal/domains/core/somedomain/somedomain.go`:
|
||||
|
||||
```go
|
||||
var errDomain = errors.New(core.DomainNameSomeDomain)
|
||||
|
||||
type domain struct {
|
||||
app *application.Application
|
||||
}
|
||||
|
||||
func Initialize(app *application.Application) error {
|
||||
dmn := &domain{
|
||||
app: app,
|
||||
}
|
||||
|
||||
if err := app.RegisterDomain(dmn); err != nil {
|
||||
return fmt.Errorf("%w: %w", errDomain, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
On application singleton's side function `(a *Application) RegisterDomain(domain Domain) error` should be implemented (see above).
|
||||
|
||||
## Domain-specific data
|
||||
|
||||
Domain-specific data should be placed in `domainname.go` file within category, e.g. `internal/domains/core/config.go` for configuration domain `internal/domains/core/config`. It should look like that:
|
||||
|
||||
```go
|
||||
package core
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"internal/domains/core/config/dto"
|
||||
)
|
||||
|
||||
// DomainNameConfig is a configuration handling domain name.
|
||||
const DomainNameConfig = "core/config"
|
||||
|
||||
// ErrConfigIsInvalid indicates that configuration domain implementation isn't conforming to its interface.
|
||||
var ErrConfigIsInvalid = errors.New(DomainNameConfig + " implementation is invalid")
|
||||
|
||||
// Config is an interface for configuration handling implementations.
|
||||
type Config interface{
|
||||
Get() *dto.Config
|
||||
}
|
||||
```
|
||||
|
||||
Where:
|
||||
|
||||
- `DomainNameConfig` is a constant with domain's name that is returned by `Name() string` function of that domain.
|
||||
- `ErrConfigIsInvalid` is a domain's error that should be exported for later use by other domains in any way (checking for presence or even returning it). There can be more than one error here.
|
||||
- `Config` is a domain-specific interface that can be used by other domains.
|
||||
|
||||
## Domain-specific interface
|
||||
|
||||
In addition to domains common interface described above, every domain might have own interface which discloses inter-domain API. That API should use only DTOs (see [DTOs and models](dtos-models.md)).
|
||||
|
||||
All signatures here should have comments describing what this function does, as these comments will be shown to end users in IDEs or editors with LSPs attached when using autocomplete or documentation browser.
|
||||
@@ -0,0 +1,59 @@
|
||||
# DTOs and models
|
||||
|
||||
Processed complex data in application should be represented with structures of two types:
|
||||
|
||||
- **DTO (Data Transfer Object)** - for inter-domain data exchange.
|
||||
- **Models** - for intra-domain data exchange.
|
||||
|
||||
Also, models are distinguished by package type:
|
||||
|
||||
- Domain models - used within domain service and responsible also for converting structures into each other. Have no tags on fields.
|
||||
- Storage models - used within storages of all kinds. Have `db` (or similar, depending on used database driver or library) tag on its fields.
|
||||
- Client models. Used in integrations with external APIs and may have `json`, `xml` or other tags on its fields.
|
||||
- Any other models that might be needed.
|
||||
|
||||
It is allowed to use embedding and nested structures if needed.
|
||||
|
||||
## DTOs
|
||||
|
||||
DTO (Data Transfer Object) is a structure that is responsible for data exchange in inter-domain APIs. This structure should not have any functions except those that are needed to operate on its data itself, e.g. comparators.
|
||||
|
||||
DTOs are placed in `dto` directory within domain, for example, `internal/domains/core/config/dto` for configuration subsystem DTOs.
|
||||
|
||||
Also initializer should be placed near it and used when creating new instance for proper structure initialization (especially if embedding is used) as well as to avoid exhaustive-like (exhaustive, exhaustive_v5 and others) linters to whine.
|
||||
|
||||
## Models
|
||||
|
||||
Model is a structure that is responsible for intra-domain data exchange and processing. Before operating on any complex data, it should be converted to model.
|
||||
|
||||
Models placement depends on model type:
|
||||
|
||||
- Domain models are placed in `models` directory within domain's root, e.g. `internal/domains/core/config/models` for configuration domain's models.
|
||||
- Storage models are placed in `models` directory within storage's root, e.g. `internal/domains/core/config/storage/postgresql/models` for PostgreSQL's data models.
|
||||
|
||||
And so on.
|
||||
|
||||
All models should contain only data they need, with notable exception of domain models, see below. For example, domain model can have 15 different fields, while storage model can have only 6 fields that represent single database row.
|
||||
|
||||
### Domain models
|
||||
|
||||
Domain models are a special kind of models as they contain not only initializers but also converters to different types of structures:
|
||||
|
||||
- Converter to DTO.
|
||||
- Converter to storage models.
|
||||
- Converter to client schema.
|
||||
- ...and so on.
|
||||
- ...and also converters from other models or schemas into domain model (like `NewFromPostgreSQLStorage`).
|
||||
|
||||
Also, unlike other types of models, domain model should have maximum possible number of fields so it can be converted to other types of models.
|
||||
|
||||
These models should not go outside of domain's service, when needed they should be converted to DTOs or other types of models:
|
||||
|
||||
- When working with database, domain models should be converted to storage models.
|
||||
- When replying to client, domain models should be converted to API schema models.
|
||||
|
||||
Point of conversion differs:
|
||||
|
||||
- When domain service itself calls storage function, domain service should convert data to storage's model and storage function accepts only own models.
|
||||
- When returning data to caller within domain, no conversion should be done, converting domain model into appropriate other model is a responsibility of caller.
|
||||
- When returning data in function that is used in inter-domain API, it should convert domain models into DTOs.
|
||||
@@ -0,0 +1,54 @@
|
||||
# Errors
|
||||
|
||||
Errors are handled using standard `error` type.
|
||||
|
||||
When neccessary (e.g. returning back to caller from another package) `fmt.Errorf` should be used.
|
||||
|
||||
General error syntax is:
|
||||
|
||||
```
|
||||
$NAME $TYPE: %w
|
||||
```
|
||||
|
||||
Where:
|
||||
|
||||
- `$NAME` is a type's name.
|
||||
- `$TYPE` is a type as string.
|
||||
|
||||
Do not try to return dynamically formatted error. If error's text (or part of it) is static - put it into a variable, and if that static text appears more than once in different functions - put it into unexported package variable.
|
||||
|
||||
Errors can be set as exported variable only if it supposed to be checked (or actually checked) in another package.
|
||||
|
||||
Good example:
|
||||
|
||||
```go
|
||||
package a
|
||||
|
||||
import "errors"
|
||||
|
||||
var errA = errors.New("a")
|
||||
|
||||
func someFunc() error {
|
||||
if err := otherFunc(); err != nil {
|
||||
return fmt.Errorf("%w: someFunc: %w", errA, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
Bad example:
|
||||
|
||||
```go
|
||||
package a
|
||||
|
||||
import errors
|
||||
|
||||
func someFunc() error {
|
||||
if err := otherFunc(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,46 @@
|
||||
# Logging
|
||||
|
||||
For logging, stdlib's `slog` package should be used as it gives everything you need for:
|
||||
|
||||
- Structured logging.
|
||||
- Debug (with appending LoC where logger's call happened).
|
||||
- Leveled logging.
|
||||
|
||||
When specially mentioned, other logging packages can be used, but approach to its usage and configuration should be the same.
|
||||
|
||||
## Configuring logger
|
||||
|
||||
Logger's configuration should be implemented with these things in mind:
|
||||
|
||||
- Logger's write destination is **always** stdout/stderr.
|
||||
- Level can be obtained from configuration or environment variable.
|
||||
- Level should be switchable at runtime.
|
||||
- LoC where logging call happened should always be added to log line.
|
||||
- Logging formatting should be configurable in same way as level.
|
||||
- Logging formatters to choose from: JSON and some pretty and readable one (like default in `slog`).
|
||||
|
||||
## Base logger
|
||||
|
||||
Base logger is initialized in Application singleton which should have function named `Logger(fields ...any) T` where `fields` are additional fields described below and `T` is a logger's type that should be returned like `*slog.Logger`. Its initialization happens when `application.New()` is called to make it accessible even in `main()` function, so when configuration is loaded it should re-initialize or re-configure (depends on used logger) base and all created sub-loggers with new logging level.
|
||||
|
||||
## Using logger in different parts of application
|
||||
|
||||
Every package in application should have own logger's instance configured that is derived from base logger with extra fields appended by default. These fields are:
|
||||
|
||||
- module - name of module (taken from `DomainName*` constants from domain-specific data, see [Domains](domains.md)).
|
||||
- type - type of submodule (e.g. "storage", "delivery", etc.).
|
||||
- name - name of submodule (e.g. "postgresql", "external HTTP", etc.).
|
||||
|
||||
For example:
|
||||
|
||||
- Main configuration domain's service:
|
||||
- module: "core/config"
|
||||
- type: "domain"
|
||||
- PostgreSQL storage in core's configuration domain should have these fields appended:
|
||||
- module: "core/config"
|
||||
- type: "storage"
|
||||
- name: "postgresql"
|
||||
- External HTTP delivery which processes client's configuration for core's configuration package:
|
||||
- module: "core/config"
|
||||
- type: "delivery"
|
||||
- name: "external HTTP"
|
||||
@@ -0,0 +1,5 @@
|
||||
# Middlewares
|
||||
|
||||
Middlewares are pieces of code that are executed on every delivery's request processing.
|
||||
|
||||
As this is a core functionality and is usually represented with a function, middlewares should be placed in `core/middlewares` domain.
|
||||
@@ -0,0 +1,11 @@
|
||||
# Storages
|
||||
|
||||
Storages are a special kind of packages that are responsible for high-level operations on storages. That said, database connections, S3 connections and other types of low-level operations are out of scope of this type of packages.
|
||||
|
||||
Storages should reside in `storage` directory in domain, e.g. for PostgreSQL configuration storage that directory will be `internal/domains/core/config/storage/postgresql`.
|
||||
|
||||
Every storage should be responsible only for one kind of storage, so PostgreSQL, MariaDB, S3 and local files storages should have own directories under `storage` directory.
|
||||
|
||||
Every storage should have own data models and should not use each other's models in function signatures. More on models in [DTOs and models](dtos-models.md).
|
||||
|
||||
Every storage should have own logger and may use other domains, so initializer should receive `*application.Application` that is used for obtaining logger and domains that implement low-level storage functions.
|
||||
@@ -0,0 +1,150 @@
|
||||
# Testing and linting
|
||||
|
||||
Project that is using these coding standards should be linted and tested on a regular basis.
|
||||
|
||||
## Linting
|
||||
|
||||
Linting should be done using [golangci-lint](https://github.com/golangci/golangci-lint) with configuration from repository.
|
||||
|
||||
If no configuration (`.golangci.yaml`) exists in project's repository, this file should be created with this content:
|
||||
|
||||
```yaml
|
||||
---
|
||||
version: "2"
|
||||
linters:
|
||||
default: all
|
||||
disable:
|
||||
- containedctx
|
||||
- depguard
|
||||
- exhaustruct
|
||||
- funlen
|
||||
- gochecknoglobals
|
||||
- gocritic
|
||||
- godot
|
||||
- iface
|
||||
- interfacebloat
|
||||
- ireturn
|
||||
- mnd
|
||||
- paralleltest
|
||||
- tagalign
|
||||
- tagliatelle
|
||||
- testpackage
|
||||
- noinlineerr
|
||||
- embeddedstructfieldcheck
|
||||
- wsl # deprecated
|
||||
- gomodguard # deprecated
|
||||
- unqueryvet # we love SELECT * when working with databases
|
||||
settings:
|
||||
cyclop:
|
||||
max-complexity: 25
|
||||
dupl:
|
||||
threshold: 400
|
||||
forbidigo:
|
||||
forbid:
|
||||
- pattern: ^(fmt\.Print(|f|ln)|print|println)$
|
||||
- pattern: ^time\.Now\(\)($|\.F|\.A|\.B|\.L|\.UTC\(\)\.I|,|\))(# Calls of time\.Now() without \.UTC() is prohibited\.)?
|
||||
funcorder:
|
||||
constructor: true
|
||||
struct-method: true
|
||||
alphabetical: true
|
||||
gocyclo:
|
||||
min-complexity: 40
|
||||
govet:
|
||||
enable-all: true
|
||||
lll:
|
||||
line-length: 120
|
||||
perfsprint:
|
||||
concat-loop: false
|
||||
revive:
|
||||
enable-all-rules: true
|
||||
rules:
|
||||
# This linter creates more problems than gives profits. Probably should be configured?
|
||||
- name: add-constant
|
||||
disabled: true
|
||||
# gocognit
|
||||
- name: cognitive-complexity
|
||||
disabled: true
|
||||
# gocyclo
|
||||
- name: cyclomatic
|
||||
disabled: true
|
||||
- name: function-length
|
||||
arguments: [200, 0]
|
||||
- name: import-alias-naming
|
||||
arguments:
|
||||
- "^[a-z][a-zA-Z0-9]{0,}$"
|
||||
- name: line-length-limit
|
||||
disabled: true
|
||||
- name: package-comments
|
||||
disabled: true
|
||||
- name: unused-receiver
|
||||
disabled: true
|
||||
- name: var-naming
|
||||
arguments:
|
||||
- ["ID"]
|
||||
- ["VM"]
|
||||
- - skipPackageNameChecks: true
|
||||
- name: package-naming
|
||||
disabled: true
|
||||
wrapcheck:
|
||||
ignore-sig-regexps:
|
||||
- \.Write\(
|
||||
- \.WriteString\(
|
||||
- \.WriteJSON\(
|
||||
- \.WriteHTML\(
|
||||
- \.Redirect\(
|
||||
- \.Error\(
|
||||
wsl_v5:
|
||||
allow-first-in-block: true
|
||||
allow-whole-block: false
|
||||
branch-max-lines: 2
|
||||
exclusions:
|
||||
generated: lax
|
||||
presets:
|
||||
- common-false-positives
|
||||
- legacy
|
||||
- std-error-handling
|
||||
rules:
|
||||
- linters:
|
||||
- godox
|
||||
text: TODO
|
||||
- linters:
|
||||
- gosec
|
||||
text: G101
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
issues:
|
||||
max-issues-per-linter: 0
|
||||
max-same-issues: 0
|
||||
uniq-by-line: false
|
||||
formatters:
|
||||
enable:
|
||||
- gofmt
|
||||
- gofumpt
|
||||
settings:
|
||||
gofumpt:
|
||||
module-path: REPLACEMEWITHGOMODMODULENAME
|
||||
extra:
|
||||
group-params: true
|
||||
clothe-returns: true
|
||||
balance-calls: true
|
||||
exclusions:
|
||||
generated: lax
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
```
|
||||
|
||||
If this file exists, AI can only suggest changes to linters configuration and provide relevant diff but should never change this file on its own.
|
||||
|
||||
## Testing
|
||||
|
||||
Testing should be done using testify package: https://github.com/stretchr/testify. When possible, test suites should be used and tests (which launch test suites) should be parallelized.
|
||||
|
||||
Mocks, when necessary, should be generated with mockery package: https://github.com/vektra/mockery. For example, mockery can be used for:
|
||||
|
||||
- Mocking external API.
|
||||
- Mocking storage layer.
|
||||
- ...and for every external communication when data goes out of application's binary to other application.
|
||||
@@ -0,0 +1,71 @@
|
||||
# Project structure
|
||||
|
||||
Project uses domain-driven design with a pinch of clean architecture.
|
||||
|
||||
Typical structure should be like this:
|
||||
|
||||
```text
|
||||
.
|
||||
├── cmd/
|
||||
│ └── binaryname/
|
||||
│ └── main.go # Binary entrypoint: domains registration, app start/shutdown.
|
||||
└── internal/
|
||||
├── application/
|
||||
│ └── application.go # Application singleton.
|
||||
├── constants/
|
||||
│ └── version.go
|
||||
└── domains/
|
||||
└── core/ # Domain category.
|
||||
└── config/ # Domain.
|
||||
├── config.go # Domain service.
|
||||
├── read.go
|
||||
├── write.go
|
||||
├── dto/ # DTOs for inter-domain API.
|
||||
│ └── configvalue.go
|
||||
├── models/ # Domain models.
|
||||
│ └── configvalue.go
|
||||
└── storage/
|
||||
└── sqlite/ # Storage implementation.
|
||||
├── storage.go
|
||||
├── read.go
|
||||
└── write.go
|
||||
```
|
||||
|
||||
Where:
|
||||
|
||||
- `internal/application` is an application singleton that is responsible for application's lifecycle (see below).
|
||||
- Every entity or business logic should be placed in own domain in `internal/domains` directory.
|
||||
- Every domain can be categorized in one category which is a directory in `internal/domains`:
|
||||
- `core` - for core functionality like GUI window, database, configuration management, etc.
|
||||
- `features` - for features, like messages pane, channels list, etc.
|
||||
- `integrations` - any other external integrations, like giphy, memegenerator, etc.
|
||||
- Any other category project might need.
|
||||
- Every domain can contain zero or more DTOs that are placed in `dto` directory in domain's root directory, e.g. `internal/domains/core/config/dto`. These DTOs are used for cross-domain calls.
|
||||
- Every domain can contain zero or more models that are placed in `models` directory in domain's root directory, e.g. `internal/domains/core/config/models`. These models are used within domain and also contain converting functions between data types like DTOs, storage models, and so on.
|
||||
- Every domain can contain zero or more storages that are tied to some low-level storage defined as domain in `internal/domains/core`. For example, SQLite database storage for configuration domain is placed in `internal/domains/core/config/storage/sqlite` and uses `internal/domains/core/sqlite` domain for its low-level actions.
|
||||
- When applicable, migrations for that storage should be placed in `migrations` directory with `embed.FS` and applied on application's startup. For example, migrations for configuration storage should be placed in `internal/domains/core/config/storage/sqlite/migrations`.
|
||||
- Domain in `protocols` or `integrations` category should contain one or more clients to external services for which this domain is responsible. E.g. `protocols/mattermost` domain should contain `client` package which is used as "proxy" between mattermost's Go client and protocol domain itself.
|
||||
|
||||
## Lines sorting in files
|
||||
|
||||
Lines in files should be sorted like this:
|
||||
|
||||
- Imports first, split in 3 groups separated by blank line:
|
||||
- First group of imports - stdlib.
|
||||
- Second group of imports - external imports.
|
||||
- Third group of imports - local dependencies.
|
||||
- Constants (`const`).
|
||||
- Variables (`var`).
|
||||
- Structure definition (`type T struct`).
|
||||
- Structure initializers (`New`, `Initialize` first class functions).
|
||||
- Functions that are tied to structure (`func (t *type) Name() string`).
|
||||
|
||||
All these groups should be sorted alphabetically, like:
|
||||
|
||||
- Import `net/http` should be after `log/slog`.
|
||||
- Variable `zetadata` should be after `megadata`.
|
||||
- Function `func (t *type) Initialize() error` should be after `func (t *type) Configure() error`.
|
||||
|
||||
---
|
||||
|
||||
For more information about every part of project see files in components directory.
|
||||
Reference in new issue
Block a user