Начальная версия

This commit is contained in:
Александр Кирюхин 2024-10-12 02:52:22 +03:00
commit d05ea66f4b
Signed by: neonxp
SSH key fingerprint: SHA256:SVt7TjxbVc87m1QYaQziOJ0N3OCFURv2g76gD/UTTXI
118 changed files with 15548 additions and 0 deletions

804
.golangci.yml Normal file
View file

@ -0,0 +1,804 @@
run:
tests: true # include test files or not, default is true
go: '1.22'
linters:
enable:
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers
- bodyclose # checks whether HTTP response body is closed successfully
- depguard # Go linter that checks if package imports are in a list of acceptable packages
- dupl # Tool for code clone detection
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
- errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13
- exhaustive # check exhaustiveness of enum switch statements and map literals
- exportloopref # checks for pointers to enclosing loop variables
- gochecknoinits # Checks that no init functions are present in Go code
- gocognit # Computes and checks the cognitive complexity of functions
- goconst # Finds repeated strings that could be replaced by a constant
- gocritic # Provides diagnostics that check for bugs, performance and style issues
- gocyclo # Computes and checks the cyclomatic complexity of functions
- godot # Check if comments end in a period
- gofmt # Gofmt checks whether code was gofmt-ed. By default, this tool runs with -s option to check for code simplification
- goheader # Checks is file header matches to pattern
- goimports # In addition to fixing imports, goimports also formats your code in the same style as gofmt
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations
- gosec # Inspects source code for security problems
- gosimple # Linter for Go source code that specializes in simplifying code
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
- ineffassign # Detects when assignments to existing variables are not used
- misspell # Finds commonly misspelled English words in comments
- nakedret # Finds naked returns in functions greater than a specified function length
- nestif # Reports deeply nested if statements
- noctx # noctx finds sending http request without context.Context
- nolintlint # Reports ill-formed or insufficient nolint directives
- paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test
- prealloc # Finds slice declarations that could potentially be pre-allocated
- revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint
- rowserrcheck # checks whether Err of rows is checked successfully
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed
- staticcheck # It's a set of rules from staticcheck. It's not the same thing as the staticcheck binary. The author of staticcheck doesn't support or approve the use of staticcheck as a library inside golangci-lint
- stylecheck # Stylecheck is a replacement for golint
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code
- unconvert # Remove unnecessary type conversions
- unparam # Reports unused function parameters
- unused # Checks Go code for unused constants, variables, functions and types
- whitespace # Tool for detection of leading and trailing whitespace
- asasalint # check for pass []any as any in variadic func(...any)
- bidichk # Checks for dangerous unicode character sequences
- containedctx # containedctx is a linter that detects struct contained context.Context field
- cyclop # checks function and package cyclomatic complexity
- decorder # check declaration order and count of types, constants, variables and functions
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
- dupword # checks for duplicate words in the source code
- durationcheck # check for two durations multiplied together
- errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted.
- errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`
- execinquery # execinquery is a linter about query string checker in Query function which reads your Go src files and warning it finds
- forbidigo # Forbids identifiers
- forcetypeassert # finds forced type assertions
- funlen # Tool for detection of long functions
- gomnd # An analyzer to detect magic numbers
- gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod
- goprintffuncname # Checks that printf-like functions are named with `f` at the end
- grouper # An analyzer to analyze expression groups
- importas # Enforces consistent import aliases
- interfacebloat # A linter that checks the number of methods inside an interface
- lll # Reports long lines
- loggercheck # Checks key valur pairs for common logger libraries (kitlog,klog,logr,zap)
- maintidx # maintidx measures the maintainability index of each function
- makezero # Finds slice declarations with non-zero initial length
- nilerr # Finds the code that returns nil even if it checks that the error is not nil
- nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value
- nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity
- nosprintfhostport # Checks for misuse of Sprintf to construct a host with port in a URL
- predeclared # find code that shadows one of Go's predeclared identifiers
- promlinter # Check Prometheus metrics naming via promlint
- reassign # Checks that package variables are not reassigned
- tagliatelle # Checks the struct tags
- tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17
- testableexamples # linter checks if examples are testable (have an expected output)
- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers
- usestdlibvars # A linter that detect the possibility to use variables/constants from the Go standard library
- varnamelen # checks that the length of a variable's name matches its scope
- wastedassign # wastedassign finds wasted assignment statements
- wsl # Whitespace Linter - Forces you to use empty lines
disable:
# [disabled]
# Use goimports instead.
- gci # Gci controls golang package import order and makes it always deterministic
# This is just a most stupid linter rule ever.
- testpackage # linter that makes you use a separate _test package
# Sometimes you really need globals.
- gochecknoglobals # check that no global variables exist
# This is stupid.
- exhaustruct # Checks if all structure fields are initialized.
# Sometimes you just have to return unwrapped error.
- wrapcheck # Checks that errors returned from external packages are wrapped.
# Not always and not everywhere.
- ireturn # Accept Interfaces, Return Concrete Types.
# They are useful to handle errors in deferred functions.
- nonamedreturns # Reports all named returns.
# Disabled because of lack of configuration. It makes a lot of unnecessary noise.
- goerr113 # Golang linter to check the errors handling expressions.
# Disabled because of the bug of reporting already sorted imports order.
- gofumpt # Gofumpt checks whether code was gofumpt-ed.
# [deprecated]
- structcheck # Finds unused struct fields
- varcheck # Finds unused global variables and constants
- deadcode # Finds unused code
- exhaustivestruct # Checks if all struct's fields are initialized
- godox # Tool for detection of FIXME, TODO and other comment keywords
- golint # Golint differs from gofmt. Gofmt reformat Go source code, whereas golint prints out style mistakes
- ifshort # Checks that your code uses short syntax for if-statements whenever possible
- interfacer # Linter that suggests narrower interface types
- maligned # Tool to detect Go structs that would take less memory if their fields were sorted
- nosnakecase # nosnakecase is a linter that detects snake case of variable naming and function name
- scopelint # Scopelint checks for unpinned variables in go programs
linters-settings:
depguard:
rules:
prevent_unmaintained_packages:
list-mode: lax # allow unless explicitely denied
files:
- $all
- "!$test"
allow:
- $gostd
deny:
- pkg: io/ioutil
desc: "replaced by io and os packages since Go 1.16: https://tip.golang.org/doc/go1.16#ioutil"
paralleltest:
# Ignore missing calls to `t.Parallel()` and only report incorrect uses of it.
# Default: false
ignore-missing: true
revive:
# Maximum number of open files at the same time.
# See https://github.com/mgechev/revive#command-line-flags
# Defaults to unlimited.
# When set to false, ignores files with "GENERATED" header, similar to golint.
# See https://github.com/mgechev/revive#available-rules for details.
# Default: false
ignore-generated-header: true
# Sets the default severity.
# See https://github.com/mgechev/revive#configuration
# Default: warning
severity: warning
# Enable all available rules.
# Default: false
enable-all-rules: true
# Sets the default failure confidence.
# This means that linting errors with less than 0.8 confidence will be ignored.
# Default: 0.8
confidence: 0.1
rules:
# Suggests using constant for magic numbers and string literals.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#add-constant
# TODO: try rule later. Looks like it is broken in 1.50.0. Use gomnd instead
- name: add-constant
severity: warning
disabled: true
arguments:
- maxLitCount: '5'
allowStrs: '""'
allowInts: '0,1,2,3,4,5,6,7,8,9,10,24,30,31'
allowFloats: '0.0,0.,1.0,1.,2.0,2.'
# Warns when a function receives more parameters than the maximum set by the rule's configuration.
# Enforcing a maximum number of parameters helps to keep the code readable and maintainable.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#argument-limit
- name: argument-limit
severity: warning
disabled: false
arguments: [ 4 ]
# Check for commonly mistaken usages of the sync/atomic package
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#atomic
- name: atomic
severity: warning
disabled: false
# Warns on bare (a.k.a. naked) returns
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#banned-characters
- name: banned-characters
severity: warning
disabled: false
arguments: [ "Ω", "Σ", "σ", "7" ]
# Checks given banned characters in identifiers(func, var, const). Comments are not checked.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#bare-return
- name: bare-return
severity: warning
disabled: false
# Blank import should be only in a main or test package, or have a comment justifying it.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#blank-imports
- name: blank-imports
severity: warning
disabled: false
# Using Boolean literals (true, false) in logic expressions may make the code less readable.
# This rule suggests removing Boolean literals from logic expressions.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#bool-literal-in-expr
- name: bool-literal-in-expr
severity: warning
disabled: false
# Explicitly invoking the garbage collector is, except for specific uses in benchmarking, very dubious.
# The garbage collector can be configured through environment variables as described here: https://pkg.go.dev/runtime
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#call-to-gc
- name: call-to-gc
severity: warning
disabled: false
# Description: Cognitive complexity is a measure of how hard code is to understand.
# While cyclomatic complexity is good to measure "testability" of the code, cognitive complexity
# aims to provide a more precise measure of the difficulty of understanding the code.
# Enforcing a maximum complexity per function helps to keep code readable and maintainable.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#cognitive-complexity
- name: cognitive-complexity
severity: warning
disabled: false
arguments: [ 30 ]
# Methods or fields of struct that have names different only by capitalization could be confusing.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#confusing-naming
- name: confusing-naming
severity: warning
disabled: false
# Function or methods that return multiple, no named, values of the same type could induce error.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#confusing-results
- name: confusing-results
severity: warning
disabled: false
# The rule spots logical expressions that evaluate always to the same value.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#constant-logical-expr
- name: constant-logical-expr
severity: warning
disabled: false
# By convention, context.Context should be the first parameter of a function.
# https://github.com/golang/go/wiki/CodeReviewComments#contexts
# This rule spots function declarations that do not follow the convention.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#context-as-argument
- name: context-as-argument
severity: warning
disabled: false
arguments: [ { allowTypesBefore = "*testing.T" } ]
# Basic types should not be used as a key in context.WithValue.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#context-keys-type
- name: context-keys-type
severity: warning
disabled: false
# Cyclomatic complexity is a measure of code complexity.
# Enforcing a maximum complexity per function helps to keep code readable and maintainable.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#cyclomatic
- name: cyclomatic
severity: warning
disabled: false
arguments: [ 15 ]
# This rule spots potential dataraces caused by go-routines capturing (by-reference) particular
# identifiers of the function from which go-routines are created.
# The rule is able to spot two of such cases: go-routines capturing named return values,
# and capturing for-range values.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#datarace
- name: datarace
severity: warning
disabled: false
# Packages exposing functions that can stop program execution by exiting are hard to reuse.
# This rule looks for program exits in functions other than main() or init().
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#deep-exit
- name: deep-exit
severity: warning
disabled: false
# This rule warns on some common mistakes when using defer statement.
# It currently alerts on the following situations:
# - [ call-chain ] - even if deferring call-chains of the form foo()() is valid,
# it does not help code understanding (only the last call is deferred)
# - [ loop ] - deferring inside loops can be misleading (deferred functions are not executed at the end
# of the loop iteration but of the current function) and it could lead to exhausting the execution stack
# - [ method-call ] - deferring a call to a method can lead to subtle bugs if the method does not have a pointer receiver
# - [ recover ] - calling recover outside a deferred function has no effect
# - [ immediate-recover ] - calling recover at the time a defer is registered, rather than as part of the deferred callback.
# e.g. defer recover() or equivalent.
# - [ return ] - returning values form a deferred function has no effect.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#defer
- name: defer
severity: warning
disabled: false
arguments:
- [ "call-chain", "loop", "method-call", "recover", "immediate-recover", "return" ]
# Importing with . makes the programs much harder to understand because it is unclear
# whether names belong to the current package or to an imported package.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#dot-imports
- name: dot-imports
severity: warning
disabled: false
# It is possible to unintentionally import the same package twice.
# This rule looks for packages that are imported two or more times.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#duplicated-imports
- name: duplicated-imports
severity: warning
disabled: false
# In GO it is idiomatic to minimize nesting statements, a typical example is to avoid if-then-else constructions.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#early-return
- name: early-return
severity: warning
disabled: false
# Empty blocks make code less readable and could be a symptom of a bug or unfinished refactoring.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#empty-block
- name: empty-block
severity: warning
disabled: false
# Sometimes gofmt is not enough to enforce a common formatting of a code-base.
# This rule warns when there are heading or trailing newlines in code blocks.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#empty-lines
- name: empty-lines
severity: warning
disabled: false
# By convention, for the sake of readability, variables of type error must be named with the prefix err.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#error-naming
- name: error-naming
severity: warning
disabled: false
# By convention, for the sake of readability, the errors should be last in the list of returned values by a function.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#error-return
- name: error-return
severity: warning
disabled: false
# By convention, for better readability, error messages should not be capitalized or end with punctuation or a newline.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#error-strings
- name: error-strings
severity: warning
disabled: false
# It is possible to get a simpler program by replacing errors.New(fmt.Sprintf()) with fmt.Errorf().
# This rule spots that kind of simplification opportunities.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#errorf
- name: errorf
severity: warning
disabled: false
# Exported function and methods should have comments.
# This warns on undocumented exported functions and methods.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#exported
- name: exported
severity: warning
disabled: false
arguments: [ ]
# This rule helps to enforce a common header for all source files in a project by spotting those files
# that do not have the specified header.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#file-header
- name: file-header
severity: warning
disabled: true
arguments: [ "" ]
# If a function controls the flow of another by passing it information on what to do, both functions are said to be control-coupled.
# Coupling among functions must be minimized for better maintainability of the code.
# This rule warns on boolean parameters that create a control coupling.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#flag-parameter
- name: flag-parameter
severity: warning
disabled: false
# Functions returning too many results can be hard to understand/use.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#function-result-limit
- name: function-result-limit
severity: warning
disabled: false
arguments: [ 2 ]
# Functions too long (with many statements and/or lines) can be hard to understand.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#function-length
- name: function-length
severity: warning
disabled: false
# (int,int) the maximum allowed statements and lines.
# Must be non-negative integers. Set to 0 to disable the check
arguments: [ 30, 0 ]
# Typically, functions with names prefixed with Get are supposed to return a value.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#get-return
- name: get-return
severity: warning
disabled: false
# An if-then-else conditional with identical implementations in both branches is an error.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#identical-branches
- name: identical-branches
severity: warning
disabled: false
# Checking if an error is nil to just after return the error or nil is redundant.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#if-return
- name: if-return
severity: warning
disabled: false
# By convention, for better readability, incrementing an integer variable by 1 is recommended
# to be done using the ++ operator.
# This rule spots expressions like i += 1 and i -= 1 and proposes to change them into i++ and i--.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#increment-decrement
- name: increment-decrement
severity: warning
disabled: false
# To improve the readability of code, it is recommended to reduce the indentation as much as possible.
# This rule highlights redundant else-blocks that can be eliminated from the code.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#indent-error-flow
- name: indent-error-flow
severity: warning
disabled: false
# Warns when importing black-listed packages.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#imports-blacklist
- name: imports-blocklist
severity: warning
disabled: false
arguments:
- "crypto/md5"
- "crypto/sha1"
# In GO it is possible to declare identifiers (packages, structs, interfaces, parameters,
# receivers, variables, constants...) that conflict with the name of an imported package.
# This rule spots identifiers that shadow an import.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#import-shadowing
- name: import-shadowing
severity: warning
disabled: false
# Warns in the presence of code lines longer than a configured maximum.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#line-length-limit
- name: line-length-limit
severity: warning
disabled: false
arguments: [ 150 ]
# Packages declaring too many public structs can be hard to understand/use,
# and could be a symptom of bad design.
# This rule warns on files declaring more than a configured, maximum number of public structs.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#max-public-structs
- name: max-public-structs
severity: warning
disabled: true
arguments: [ 3 ]
# A function that modifies its parameters can be hard to understand.
# It can also be misleading if the arguments are passed by value by the caller.
# This rule warns when a function modifies one or more of its parameters.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#modifies-parameter
- name: modifies-parameter
severity: warning
disabled: false
# A method that modifies its receiver value can have undesired behavior.
# The modification can be also the root of a bug because the actual value receiver could be a copy of that used at the calling site.
# This rule warns when a method modifies its receiver.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#modifies-value-receiver
- name: modifies-value-receiver
severity: warning
disabled: false
# Packages declaring structs that contain other inline struct definitions can be hard to understand/read for other developers.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#nested-structs
- name: nested-structs
severity: warning
disabled: false
# conditional expressions can be written to take advantage of short circuit evaluation and speed up
# its average evaluation time by forcing the evaluation of less time-consuming terms before more costly ones.
# This rule spots logical expressions where the order of evaluation of terms seems non-optimal.
# Please notice that confidence of this rule is low and is up to the user to decide if the suggested
# rewrite of the expression keeps the semantics of the original one.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#optimize-operands-order
- name: optimize-operands-order
severity: warning
disabled: false
# Packages should have comments. This rule warns on undocumented packages and when packages comments are detached to the package keyword.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#package-comments
- name: package-comments
severity: warning
disabled: false
# This rule suggests a shorter way of writing ranges that do not use the second value.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#range
- name: range
severity: warning
disabled: false
# Range variables in a loop are reused at each iteration; therefore a goroutine created
# in a loop will point to the range variable with from the upper scope.
# This way, the goroutine could use the variable with an undesired value.
# This rule warns when a range value (or index) is used inside a closure.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#range-val-in-closure
- name: range-val-in-closure
severity: warning
disabled: false
# Range variables in a loop are reused at each iteration. This rule warns when assigning the address of the variable,
# passing the address to append() or using it in a map.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#range-val-address
- name: range-val-address
severity: warning
disabled: false
# By convention, receiver names in a method should reflect their identity.
# For example, if the receiver is of type Parts, p is an adequate name for it.
# Contrary to other languages, it is not idiomatic to name receivers as this or self.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#receiver-naming
- name: receiver-naming
severity: warning
disabled: false
# Constant names like false, true, nil, function names like append, make, and basic type names like bool,
# and byte are not reserved words of the language; therefore the can be redefined.
# Even if possible, redefining these built in names can lead to bugs very difficult to detect.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#redefines-builtin-id
- name: redefines-builtin-id
severity: warning
disabled: false
# explicit type conversion string(i) where i has an integer type other than
# rune might behave not as expected by the developer (e.g. string(42) is not "42").
# This rule spot that kind of suspicious conversions.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#string-of-int
- name: string-of-int
severity: warning
disabled: false
# This rule allows you to configure a list of regular expressions that string literals
# in certain function calls are checked against. This is geared towards user facing applications
# where string literals are often used for messages that will be presented to users,
# so it may be desirable to enforce consistent formatting.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#string-format
- name: string-format
severity: warning
disabled: true
arguments: [ ]
# Struct tags are not checked at compile time.
# This rule, checks and warns if it finds errors in common struct tags types like:
# asn1, default, json, protobuf, xml, yaml.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#struct-tag
- name: struct-tag
severity: warning
disabled: false
# To improve the readability of code, it is recommended to reduce the indentation as much as possible.
# This rule highlights redundant else-blocks that can be eliminated from the code.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#superfluous-else
- name: superfluous-else
severity: warning
disabled: false
# This rule warns when using == and != for equality check time.Time and suggest to time.time.Equal method,
# for about information follow this link: https://pkg.go.dev/time#Time
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#time-equal
- name: time-equal
severity: warning
disabled: false
# Using unit-specific suffix like "Secs", "Mins", ... when naming variables of type time.Duration
# can be misleading, this rule highlights those cases.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#time-naming
- name: time-naming
severity: warning
disabled: false
# This rule warns when initialism, variable or package naming conventions are not followed.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#var-naming
- name: var-naming
severity: warning
disabled: false
arguments:
- [ ] # AllowList
- [ "ID", "VM" ] # DenyList
# This rule proposes simplifications of variable declarations.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#var-declaration
- name: var-declaration
severity: warning
disabled: false
# Unconditional recursive calls will produce infinite recursion, thus program stack overflow.
# This rule detects and warns about unconditional (direct) recursive calls.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unconditional-recursion
- name: unconditional-recursion
severity: warning
disabled: false
# This rule warns on wrongly named un-exported symbols, i.e. un-exported symbols whose name
# start with a capital letter.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unexported-naming
- name: unexported-naming
severity: warning
disabled: false
# This rule warns when an exported function or method returns a value of an un-exported type.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unexported-return
- name: unexported-return
severity: warning
disabled: false
# This rule warns when errors returned by a function are not explicitly handled on the caller side.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unhandled-error
- name: unhandled-error
severity: warning
disabled: false
arguments:
- "fmt.Println"
- "fmt.Printf"
# This rule suggests to remove redundant statements like a break at the end of a case block,
# for improving the code's readability.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unnecessary-stmt
- name: unnecessary-stmt
severity: warning
disabled: false
# This rule spots and proposes to remove unreachable code.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unreachable-code
- name: unreachable-code
severity: warning
disabled: false
# This rule warns on unused parameters. Functions or methods with unused parameters can be a symptom of an unfinished refactoring or a bug.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unused-parameter
- name: unused-parameter
severity: warning
disabled: false
# This rule warns on unused method receivers.
# Methods with unused receivers can be a symptom of an unfinished refactoring or a bug.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unused-receiver
- name: unused-receiver
severity: warning
disabled: false
# This rule warns on useless break statements in case clauses of switch and select statements.
# GO, unlike other programming languages like C, only executes statements of the selected case
# while ignoring the subsequent case clauses.
# Therefore, inserting a break at the end of a case clause has no effect.
# Because break statements are rarely used in case clauses, when switch or select statements
# are inside a for-loop, the programmer might wrongly assume that a break in a case clause will
# take the control out of the loop. The rule emits a specific warning for such cases.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#useless-break
- name: useless-break
severity: warning
disabled: false
# Function parameters that are passed by value, are in fact a copy of the original argument.
# Passing a copy of a sync.WaitGroup is usually not what the developer wants to do.
# This rule warns when a sync.WaitGroup expected as a by-value parameter in a function or method.
# https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#waitgroup-by-value
- name: waitgroup-by-value
severity: warning
disabled: false
forbidigo:
# Forbid the following identifiers (list of regexp).
# Default: ["^(fmt\\.Print(|f|ln)|print|println)$"]
forbid:
# Optionally put comments at the end of the regex, surrounded by `(# )?`
# Escape any special characters.
- '^print.*$(# print statements should not be committed)'
# Exclude godoc examples from forbidigo checks.
# Default: true
exclude-godoc-examples: true
cyclop:
# The maximal code complexity to report.
# Default: 10
max-complexity: 15
# The maximal average package complexity.
# If it's higher than 0.0 (float) the check is enabled
# Default: 0.0
package-average: 6
# Should ignore tests.
# Default: false
skip-tests: true
funlen:
# Checks the number of lines in a function.
# If lower than 0, disable the check.
# Default: 60
lines: 200
# Checks the number of statements in a function.
# If lower than 0, disable the check.
# Default: 40
statements: 50
tagliatelle:
# Check the struck tag name case.
case:
# Use the struct field name to check the name of the struct tag.
# Default: false
use-field-name: false
# `camel` is used for `json` and `yaml` (can be overridden)
# Default: {}
rules:
# Any struct tag type can be used.
# Support string case: `camel`, `pascal`, `kebab`, `snake`, `goCamel`, `goPascal`, `goKebab`, `goSnake`, `upper`, `lower`
json: snake
yaml: camel
xml: camel
bson: camel
avro: snake
mapstructure: kebab
varnamelen:
# The longest distance, in source lines, that is being considered a "small scope".
# Variables used in at most this many lines will be ignored.
# Default: 5
max-distance: 10
# The minimum length of a variable's name that is considered "long".
# Variable names that are at least this long will be ignored.
# Default: 3
min-name-length: 1
# Check method receivers.
# Default: false
check-receiver: true
# Check named return values.
# Default: false
check-return: true
# Check type parameters.
# Default: false
check-type-param: true
# Ignore "ok" variables that hold the bool return value of a type assertion.
# Default: false
ignore-type-assert-ok: true
# Ignore "ok" variables that hold the bool return value of a map index.
# Default: false
ignore-map-index-ok: true
# Ignore "ok" variables that hold the bool return value of a channel receive.
# Default: false
ignore-chan-recv-ok: true
# Optional list of variable names that should be ignored completely.
# Default: []
ignore-names:
- err
# Optional list of variable declarations that should be ignored completely.
# Entries must be in one of the following forms (see below for examples):
# - for variables, parameters, named return values, method receivers, or type parameters:
# <name> <type> (<type> can also be a pointer/slice/map/chan/...)
# - for constants: const <name>
#
# Default: []
ignore-decls:
- t testing.T
- e error
- i int
- T any
lll:
# Max line length, lines longer will be reported.
# '\t' is counted as 1 character by default, and can be changed with the tab-width option.
# Default: 120.
line-length: 150
# Tab width in spaces.
# Default: 1
tab-width: 1
nlreturn:
# Size of the block (including return statement that is still "OK")
# so no return split required.
# Default: 1
block-size: 3
wsl:
# See https://github.com/bombsimon/wsl/blob/master/doc/configuration.md for
# documentation of available settings. These are the defaults for golangci-lint.
allow-assign-and-anything: false
allow-assign-and-call: true
allow-cuddle-declarations: false
allow-multiline-assign: true
allow-separated-leading-comment: false
allow-trailing-comment: false
force-case-trailing-whitespace: 0
force-err-cuddling: false
force-short-decl-cuddling: false
strict-append: true

10
.vscode/extensions.json vendored Normal file
View file

@ -0,0 +1,10 @@
{
"recommendations": [
"golang.go",
"craigrbroughton.htmx-attributes",
"carlos-algms.make-task-provider",
"a-h.templ",
"mtxr.sqltools",
"mtxr.sqltools-driver-pg"
]
}

19
.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,19 @@
{
// Используйте IntelliSense, чтобы узнать о возможных атрибутах.
// Наведите указатель мыши, чтобы просмотреть описания существующих атрибутов.
// Для получения дополнительной информации посетите: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch Package",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/cmd/app",
"args": [
"serve", "-config", "./etc/dev.yaml"
],
"cwd": "${workspaceFolder}"
}
]
}

23
Dockerfile Normal file
View file

@ -0,0 +1,23 @@
# Build backend
FROM golang:1.23.2-alpine3.20 AS backend
ARG VERSION
WORKDIR /srv
RUN apk update --no-cache && apk add --no-cache tzdata
COPY go.mod go.sum ./
RUN go mod download && go mod verify
COPY . .
RUN go build -o app ./cmd/app
# Runtime container
FROM alpine:3.20
WORKDIR /srv
RUN apk update --no-cache && apk add --no-cache ca-certificates
COPY --from=backend /usr/share/zoneinfo/Europe/Moscow /usr/share/zoneinfo/Europe/Moscow
COPY --from=backend /srv/app /srv/app
ENV TZ=Europe/Moscow
EXPOSE 8000
ENTRYPOINT ["/srv/app"]

235
LICENSE Normal file
View file

@ -0,0 +1,235 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
ShOrgRu
Copyright (C) 2024 NeonXP
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.

44
Makefile Normal file
View file

@ -0,0 +1,44 @@
.PHONY: dev-infra-up
dev-infra-up:
docker compose -f ./contrib/dev/docker-compose.yml up -d
.PHONY: dev-infra-stop
dev-infra-stop:
docker compose -f ./contrib/dev/docker-compose.yml stop
.PHONY: dev-infra-down
dev-infra-down:
docker compose -f ./contrib/dev/docker-compose.yml down
.PHONY: generate
generate:
go generate ./...
templ generate
.PHONY: tidyvendor
tidyvendor:
go mod tidy
go mod vendor
.PHONY: init-dev
init-dev:
go run ./cmd/app db init --config ./etc/dev.yaml
.PHONY: migrate-dev
migrate-dev:
go run ./cmd/app db migrate --config ./etc/dev.yaml
.PHONY: rollback-dev
rollback-dev:
go run ./cmd/app db rollback --config ./etc/dev.yaml
.PHONY: init-prod
init-prod:
go run ./cmd/app db init --config ./etc/prod.yaml
.PHONY: migrate-prod
migrate-prod:
go run ./cmd/app db migrate --config ./etc/prod.yaml
.PHONY: rollback-prod
rollback-prod:
go run ./cmd/app db rollback --config ./etc/prod.yaml
# .PHONY: deploy
# deploy: generate
# docker build -t gitrepo.ru/neonxp/shorg:latest .
# docker push gitrepo.ru/neonxp/shorg:latest
# docker context use curie
# docker compose -f ./contrib/prod/docker-compose.yml --project-name shorg pull app
# docker compose -f ./contrib/prod/docker-compose.yml --project-name shorg up --force-recreate --build -d
# docker image prune -f
# docker context use default

19
README.md Normal file
View file

@ -0,0 +1,19 @@
# Framework
```sh
go install golang.org/x/tools/cmd/gonew@latest
gonew go.neonxp.ru/framework example.com/myproject
```
Запуск БД для разработки:
```sh
make dev-infra-up
```
Миграция
```sh
make init-dev
make migrate-dev
```

34
cmd/app/main.go Normal file
View file

@ -0,0 +1,34 @@
package main
import (
"log"
"os"
"github.com/urfave/cli/v2"
"go.neonxp.ru/framework/cmd/app/migrator"
"go.neonxp.ru/framework/cmd/app/serve"
)
func main() {
app := &cli.App{
Name: "app",
Commands: []*cli.Command{
{
Name: "serve",
Action: serve.Run,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "config",
Value: "./config/dev.yaml",
Usage: "config",
},
},
},
migrator.Migrator(),
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}

View file

@ -0,0 +1,16 @@
package migrate
import (
"github.com/urfave/cli/v2"
"go.neonxp.ru/framework/cmd/app/migrator/migrator"
"go.neonxp.ru/framework/migrations"
)
func Init(c *cli.Context) error {
m, err := migrator.New(c, migrations.Migrations)
if err != nil {
return err
}
return m.Init(c.Context)
}

View file

@ -0,0 +1,30 @@
package migrate
import (
"fmt"
"github.com/urfave/cli/v2"
"go.neonxp.ru/framework/cmd/app/migrator/migrator"
"go.neonxp.ru/framework/migrations"
)
func Migrate(c *cli.Context) error {
m, err := migrator.New(c, migrations.Migrations)
if err != nil {
return err
}
group, err := m.Migrate(c.Context)
if err != nil {
return err
}
if group.ID == 0 {
fmt.Printf("there are no new migrations to run\n")
return nil
}
fmt.Printf("migrated to %s\n", group)
return nil
}

View file

@ -0,0 +1,30 @@
package migrate
import (
"fmt"
"github.com/urfave/cli/v2"
"go.neonxp.ru/framework/cmd/app/migrator/migrator"
"go.neonxp.ru/framework/migrations"
)
func Rollback(c *cli.Context) error {
m, err := migrator.New(c, migrations.Migrations)
if err != nil {
return err
}
group, err := m.Rollback(c.Context)
if err != nil {
return err
}
if group.ID == 0 {
fmt.Printf("there are no groups to roll back\n")
return nil
}
fmt.Printf("rolled back %s\n", group)
return nil
}

View file

@ -0,0 +1,83 @@
package migrator
import (
"fmt"
"strings"
"github.com/urfave/cli/v2"
"go.neonxp.ru/framework/cmd/app/migrator/migrate"
"go.neonxp.ru/framework/cmd/app/migrator/migrator"
"go.neonxp.ru/framework/migrations"
)
func Migrator() *cli.Command {
return &cli.Command{
Name: "db",
Usage: "manage database migrations",
Subcommands: []*cli.Command{
{
Name: "init",
Usage: "create migration tables",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "config",
Value: "./config/config.yaml",
Usage: "config",
},
},
Action: migrate.Init,
},
{
Name: "migrate",
Usage: "migrate database",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "config",
Value: "./config/config.yaml",
Usage: "config",
},
},
Action: migrate.Migrate,
},
{
Name: "rollback",
Usage: "rollback the last migration group",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "config",
Value: "./config/config.yaml",
Usage: "config",
},
},
Action: migrate.Rollback,
},
{
Name: "create",
Usage: "create migration",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "config",
Value: "./config/config.yaml",
Usage: "config",
},
},
Action: func(c *cli.Context) error {
migrator, err := migrator.New(c, migrations.Migrations)
if err != nil {
return err
}
name := strings.Join(c.Args().Slice(), "_")
mf, err := migrator.CreateGoMigration(c.Context, name)
if err != nil {
return err
}
fmt.Printf("created migration %s (%s)\n", mf.Name, mf.Path)
return nil
},
},
},
}
}

View file

@ -0,0 +1,23 @@
package migrator
import (
"github.com/uptrace/bun/migrate"
"github.com/urfave/cli/v2"
"go.neonxp.ru/framework/pkg/config"
"go.neonxp.ru/framework/pkg/db"
)
func New(c *cli.Context, mig *migrate.Migrations) (*migrate.Migrator, error) {
configFile := c.String("config")
cfg, err := config.New(configFile)
if err != nil {
return nil, err
}
dbClient := db.New(cfg.DB)
migrator := migrate.NewMigrator(dbClient, mig)
return migrator, nil
}

56
cmd/app/serve/serve.go Normal file
View file

@ -0,0 +1,56 @@
package serve
import (
echosession "github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
echomiddleware "github.com/labstack/echo/v4/middleware"
"github.com/uptrace/bun/extra/bundebug"
"github.com/urfave/cli/v2"
"go.neonxp.ru/framework/pkg/config"
"go.neonxp.ru/framework/pkg/db"
"go.neonxp.ru/framework/pkg/handler"
"go.neonxp.ru/framework/pkg/handler/user"
"go.neonxp.ru/framework/pkg/middleware"
"go.neonxp.ru/framework/pkg/middleware/session"
userservice "go.neonxp.ru/framework/pkg/service/user"
"go.neonxp.ru/framework/static"
)
func Run(c *cli.Context) error {
configFile := c.String("config")
cfg, err := config.New(configFile)
if err != nil {
return err
}
dbClient := db.New(cfg.DB)
dbClient.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(cfg.Debug)))
store, err := session.New(dbClient, cfg.Keypairs)
if err != nil {
return err
}
e := echo.New()
e.HTTPErrorHandler = handler.ErrorHandler
e.Use(
echomiddleware.Recover(),
echomiddleware.Logger(),
echomiddleware.RemoveTrailingSlash(),
echosession.Middleware(store),
middleware.Context("config", cfg),
middleware.User(),
)
userService := userservice.NewService(dbClient)
router := handler.Router{
"/user": user.NewHandler(userService),
}
router.Register(e)
e.StaticFS("/", static.FS)
return e.Start(cfg.Listen)
}

View file

@ -0,0 +1,20 @@
version: '3.9'
services:
db:
image: postgres
restart: always
shm_size: 128mb
environment:
POSTGRES_DB: app
POSTGRES_USER: app
POSTGRES_PASSWORD: app
ports:
- 5432:5432
adminer:
image: adminer
restart: always
ports:
- 8090:8080

3
contrib/prod/.env Normal file
View file

@ -0,0 +1,3 @@
POSTGRES_DB=shorg
POSTGRES_USER=shorg
POSTGRES_PASSWORD=shorg

View file

@ -0,0 +1,37 @@
version: '3.3'
services:
db:
image: postgres
shm_size: 128mb
env_file: .env
volumes:
- data:/var/lib/postgresql/data
healthcheck:
test: [ "CMD-SHELL", "pg_isready -U app -d app" ]
interval: 30s
timeout: 30s
retries: 5
restart: unless-stopped
app:
image: gitrepo.ru/neonxp/app:latest
volumes:
- config:/config
command: serve -config=/config/prod.yaml
depends_on:
db:
condition: service_healthy
ports:
- 8093:8000
restart: unless-stopped
migration:
image: gitrepo.ru/neonxp/app:latest
volumes:
- config:/config
command: db migrate -config=/config/prod.yaml
depends_on:
db:
condition: service_healthy
volumes:
data:
config:

15
etc/dev.yaml Normal file
View file

@ -0,0 +1,15 @@
debug: true
db:
dsn: "postgres://app:app@localhost:5432/app?sslmode=disable"
listen: :8000
admins:
admin: password
host: https://sh.org.ru
keys:
- 12345678901234567890123456789012
- 12345678901234567890123456789012

15
etc/prod.yaml Normal file
View file

@ -0,0 +1,15 @@
debug: true
db:
dsn: "postgres://app:app@db:5432/app?sslmode=disable"
listen: :8000
admins:
admin: password
host: https://sh.org.ru
keys:
- 12345678901234567890123456789012
- 12345678901234567890123456789012

46
go.mod Normal file
View file

@ -0,0 +1,46 @@
module go.neonxp.ru/framework
go 1.23
require (
github.com/a-h/templ v0.2.778
github.com/gorilla/securecookie v1.1.2
github.com/gorilla/sessions v1.4.0
github.com/labstack/echo-contrib v0.17.1
github.com/uptrace/bun v1.2.3
github.com/uptrace/bun/extra/bundebug v1.2.3
github.com/urfave/cli/v2 v2.27.4
golang.org/x/crypto v0.26.0
gopkg.in/yaml.v3 v3.0.1
)
require (
github.com/cpuguy83/go-md2man/v2 v2.0.4 // indirect
github.com/fatih/color v1.17.0 // indirect
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
github.com/gorilla/context v1.1.2 // indirect
github.com/labstack/gommon v0.4.2 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect
golang.org/x/net v0.28.0 // indirect
golang.org/x/text v0.17.0 // indirect
golang.org/x/time v0.5.0 // indirect
mellium.im/sasl v0.3.1 // indirect
)
require (
github.com/dimuska139/go-email-normalizer/v3 v3.0.1
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/labstack/echo/v4 v4.12.0
github.com/puzpuzpuz/xsync/v3 v3.4.0 // indirect
github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc // indirect
github.com/uptrace/bun/dialect/pgdialect v1.2.3
github.com/uptrace/bun/driver/pgdriver v1.2.3
github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
golang.org/x/sys v0.24.0 // indirect
)

92
go.sum Normal file
View file

@ -0,0 +1,92 @@
github.com/a-h/templ v0.2.778 h1:VzhOuvWECrwOec4790lcLlZpP4Iptt5Q4K9aFxQmtaM=
github.com/a-h/templ v0.2.778/go.mod h1:lq48JXoUvuQrU0VThrK31yFwdRjTCnIE5bcPCM9IP1w=
github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dimuska139/go-email-normalizer/v3 v3.0.1 h1:4XKdhuemUESTvp+UpSMRz7PvTnQOJS+L9TD1NzRKpMI=
github.com/dimuska139/go-email-normalizer/v3 v3.0.1/go.mod h1:CFFQ5NlrwTRotzaWFc4WWuVyLBqSZEeFQ0TJwtGxt4U=
github.com/fatih/color v1.17.0 h1:GlRw1BRJxkpqUCBKzKOw098ed57fEsKeNjpTe3cSjK4=
github.com/fatih/color v1.17.0/go.mod h1:YZ7TlrGPkiz6ku9fK3TLD/pl3CpsiFyu8N92HLgmosI=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/gorilla/context v1.1.2 h1:WRkNAv2uoa03QNIc1A6u4O7DAGMUVoopZhkiXWA2V1o=
github.com/gorilla/context v1.1.2/go.mod h1:KDPwT9i/MeWHiLl90fuTgrt4/wPcv75vFAZLaOOcbxM=
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=
github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/labstack/echo-contrib v0.17.1 h1:7I/he7ylVKsDUieaGRZ9XxxTYOjfQwVzHzUYrNykfCU=
github.com/labstack/echo-contrib v0.17.1/go.mod h1:SnsCZtwHBAZm5uBSAtQtXQHI3wqEA73hvTn0bYMKnZA=
github.com/labstack/echo/v4 v4.12.0 h1:IKpw49IMryVB2p1a4dzwlhP1O2Tf2E0Ir/450lH+kI0=
github.com/labstack/echo/v4 v4.12.0/go.mod h1:UP9Cr2DJXbOK3Kr9ONYzNowSh7HP0aG0ShAyycHSJvM=
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/puzpuzpuz/xsync/v3 v3.4.0 h1:DuVBAdXuGFHv8adVXjWWZ63pJq+NRXOWVXlKDBZ+mJ4=
github.com/puzpuzpuz/xsync/v3 v3.4.0/go.mod h1:VjzYrABPabuM4KyBh1Ftq6u8nhwY5tBPKP9jpmh0nnA=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc h1:9lRDQMhESg+zvGYmW5DyG0UqvY96Bu5QYsTLvCHdrgo=
github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc/go.mod h1:bciPuU6GHm1iF1pBvUfxfsH0Wmnc2VbpgvbI9ZWuIRs=
github.com/uptrace/bun v1.2.3 h1:6KDc6YiNlXde38j9ATKufb8o7MS8zllhAOeIyELKrk0=
github.com/uptrace/bun v1.2.3/go.mod h1:8frYFHrO/Zol3I4FEjoXam0HoNk+t5k7aJRl3FXp0mk=
github.com/uptrace/bun/dialect/pgdialect v1.2.3 h1:YyCxxqeL0lgFWRZzKCOt6mnxUsjqITcxSo0mLqgwMUA=
github.com/uptrace/bun/dialect/pgdialect v1.2.3/go.mod h1:Vx9TscyEq1iN4tnirn6yYGwEflz0KG3rBZTBCLpKAjc=
github.com/uptrace/bun/driver/pgdriver v1.2.3 h1:VA5TKB0XW7EtreQq2R8Qu/vCAUX2ECaprxGKI9iDuDE=
github.com/uptrace/bun/driver/pgdriver v1.2.3/go.mod h1:yDiYTZYd4FfXFtV01m4I/RkI33IGj9N254jLStaeJLs=
github.com/uptrace/bun/extra/bundebug v1.2.3 h1:2QBykz9/u4SkN9dnraImDcbrMk2fUhuq2gL6hkh9qSc=
github.com/uptrace/bun/extra/bundebug v1.2.3/go.mod h1:bihsYJxXxWZXwc1R3qALTHvp+npE0ElgaCvcjzyPPdw=
github.com/urfave/cli/v2 v2.27.4 h1:o1owoI+02Eb+K107p27wEX9Bb8eqIoZCfLXloLUSWJ8=
github.com/urfave/cli/v2 v2.27.4/go.mod h1:m4QzxcD2qpra4z7WhzEGn74WZLViBnMpb1ToCAKdGRQ=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8=
github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok=
github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=
github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 h1:gEOO8jv9F4OT7lGCjxCBTO/36wtF6j2nSip77qHd4x4=
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM=
golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw=
golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54=
golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE=
golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc=
golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
mellium.im/sasl v0.3.1 h1:wE0LW6g7U83vhvxjC1IY8DnXM+EU095yeo8XClvCdfo=
mellium.im/sasl v0.3.1/go.mod h1:xm59PUYpZHhgQ9ZqoJ5QaCqzWMi8IeS49dhp6plPCzw=

View file

@ -0,0 +1,30 @@
package migrations
import (
"context"
"fmt"
"github.com/uptrace/bun"
"go.neonxp.ru/framework/pkg/model"
)
//nolint:gochecknoinits
func init() {
Migrations.MustRegister(func(ctx context.Context, db *bun.DB) error {
fmt.Print(" [up migration] ")
if _, err := db.NewCreateTable().Model((*model.User)(nil)).Exec(ctx); err != nil {
return err
}
return nil
}, func(ctx context.Context, db *bun.DB) error {
fmt.Print(" [down migration] ")
if _, err := db.NewDropTable().Model((*model.User)(nil)).Exec(ctx); err != nil {
return err
}
return nil
})
}

View file

@ -0,0 +1,34 @@
package migrations
import (
"context"
"fmt"
"github.com/uptrace/bun"
"go.neonxp.ru/framework/pkg/middleware/session"
)
//nolint:gochecknoinits
func init() {
Migrations.MustRegister(func(ctx context.Context, db *bun.DB) error {
fmt.Print(" [up migration] ")
if _, err := db.NewCreateTable().
Model((*session.Model)(nil)).
Exec(ctx); err != nil {
return err
}
return nil
}, func(ctx context.Context, db *bun.DB) error {
fmt.Print(" [down migration] ")
if _, err := db.NewDropTable().
Model((*session.Model)(nil)).
Exec(ctx); err != nil {
return err
}
return nil
})
}

7
migrations/main.go Normal file
View file

@ -0,0 +1,7 @@
package migrations
import (
"github.com/uptrace/bun/migrate"
)
var Migrations = migrate.NewMigrations()

27
pkg/config/config.go Normal file
View file

@ -0,0 +1,27 @@
package config
import (
"os"
"go.neonxp.ru/framework/pkg/db"
"gopkg.in/yaml.v3"
)
type Config struct {
Debug bool `yaml:"debug"`
DB *db.Config `yaml:"db"`
Listen string `yaml:"listen"`
Host string `yaml:"host"`
Admins map[string]string `yaml:"admins"`
Keypairs []string `yaml:"keys"`
}
func New(file string) (*Config, error) {
cfg := new(Config)
fp, err := os.Open(file)
if err != nil {
return nil, err
}
return cfg, yaml.NewDecoder(fp).Decode(cfg)
}

5
pkg/db/config.go Normal file
View file

@ -0,0 +1,5 @@
package db
type Config struct {
DSN string `yaml:"dsn"`
}

18
pkg/db/db.go Normal file
View file

@ -0,0 +1,18 @@
package db
import (
"database/sql"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/driver/pgdriver"
)
// dsn := "postgres://postgres:@localhost:5432/test?sslmode=disable"
// dsn := "unix://user:pass@dbname/var/run/postgresql/.s.PGSQL.5432"
func New(config *Config) *bun.DB {
sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(config.DSN)))
return bun.NewDB(sqldb, pgdialect.New())
}

47
pkg/handler/error.go Normal file
View file

@ -0,0 +1,47 @@
package handler
import (
"log"
"net/http"
"github.com/labstack/echo/v4"
"go.neonxp.ru/framework/pkg/tpl"
)
func ErrorHandler(err error, c echo.Context) {
if c.Response().Committed {
return
}
he, ok := err.(*echo.HTTPError)
if ok {
if he.Internal != nil {
if herr, ok := he.Internal.(*echo.HTTPError); ok {
he = herr
}
}
} else {
he = &echo.HTTPError{
Code: http.StatusInternalServerError,
Message: http.StatusText(http.StatusInternalServerError),
}
}
code := he.Code
message, ok := he.Message.(string)
if !ok {
message = "Неизвестная ошибка"
}
if c.Request().Method == http.MethodHead {
err = c.NoContent(he.Code)
} else {
c.Response().WriteHeader(code)
if err := tpl.ErrorPage(code, message).
Render(c.Request().Context(), c.Response()); err != nil {
log.Println(err)
}
}
if err != nil {
log.Println(err)
}
}

15
pkg/handler/handler.go Normal file
View file

@ -0,0 +1,15 @@
package handler
import "github.com/labstack/echo/v4"
type Handler interface {
Register(g *echo.Group)
}
type Router map[string]Handler
func (r Router) Register(e *echo.Echo) {
for groupName, handlers := range r {
handlers.Register(e.Group(groupName))
}
}

View file

@ -0,0 +1,30 @@
package user
import (
"errors"
"go.neonxp.ru/framework/pkg/service/user"
)
var UserErrors = Errors{
user.ErrInvalidUserOrPassword: "Неверный email или пароль",
user.ErrPasswordTooShort: "Пароль слишком короткий",
user.ErrPasswordTooWeak: "Пароль слишком простой",
user.ErrUserAlreadyExist: "Пользователь уже существует",
user.ErrUsernameToShort: "Имя пользователя слишком короткое",
// user.ErrEmailEmpty: "Электропочта не указана",
// user.ErrPasswordEmpty: "Пароль не указан",
// user.ErrNameEmpty: "Имя пользователя не указано",
}
type Errors map[error]string
func (e Errors) Get(err error) string {
for target, msg := range e {
if errors.Is(err, target) {
return msg
}
}
return ""
}

View file

@ -0,0 +1,24 @@
package user
import (
"github.com/labstack/echo/v4"
"go.neonxp.ru/framework/pkg/service/user"
)
type Handler struct {
user *user.Service
}
// NewHandler returns new Handler.
func NewHandler(u *user.Service) *Handler {
return &Handler{user: u}
}
func (h *Handler) Register(g *echo.Group) {
g.GET("/login", h.LoginForm)
g.POST("/login", h.LoginForm)
g.GET("/register", h.RegisterForm)
g.POST("/register", h.RegisterForm)
g.GET("/profile", h.Profile)
g.POST("/logout", h.Logout)
}

53
pkg/handler/user/login.go Normal file
View file

@ -0,0 +1,53 @@
package user
import (
"net/http"
"github.com/labstack/echo/v4"
"go.neonxp.ru/framework/pkg/tpl"
"go.neonxp.ru/framework/pkg/utils"
)
const oneyear = 86400 * 365
func (h *Handler) LoginForm(c echo.Context) error {
form := &tpl.LoginForm{}
if err := c.Bind(form); err != nil {
return err
}
if c.Request().Method == http.MethodPost {
err := h.doLogin(c, form)
if err == nil {
if utils.IsHTMX(c) {
utils.HTMXRedirect(c, "/")
return c.NoContent(http.StatusNoContent)
}
return c.Redirect(http.StatusFound, "/")
}
form.Message = UserErrors.Get(err)
if form.Message == "" {
return err
}
}
return tpl.Login(form).
Render(c.Request().Context(), c.Response())
}
func (h *Handler) doLogin(c echo.Context, form *tpl.LoginForm) error {
u, err := h.user.Login(c.Request().Context(), form)
if err != nil {
return err
}
maxage := 0
if form.Remember == "on" {
maxage = oneyear
}
return utils.SetUser(c, u, maxage)
}

View file

@ -0,0 +1,18 @@
package user
import (
"net/http"
"github.com/labstack/echo/v4"
"go.neonxp.ru/framework/pkg/utils"
)
func (*Handler) Logout(c echo.Context) error {
if err := utils.SetUser(c, nil, -1); err != nil {
return err
}
utils.HTMXRedirect(c, "/")
return c.NoContent(http.StatusNoContent)
}

View file

@ -0,0 +1,16 @@
package user
import (
"github.com/labstack/echo/v4"
"go.neonxp.ru/framework/pkg/tpl"
"go.neonxp.ru/framework/pkg/utils"
)
func (*Handler) Profile(c echo.Context) error {
u := utils.GetUserCtx(c.Request().Context())
if u == nil {
return echo.ErrForbidden
}
return tpl.Profile(u).Render(c.Request().Context(), c.Response())
}

View file

@ -0,0 +1,45 @@
package user
import (
"net/http"
"github.com/labstack/echo/v4"
"go.neonxp.ru/framework/pkg/tpl"
"go.neonxp.ru/framework/pkg/utils"
)
func (h *Handler) RegisterForm(c echo.Context) error {
form := &tpl.RegisterForm{}
if err := c.Bind(form); err != nil {
return err
}
if c.Request().Method == http.MethodPost {
err := h.doRegister(c, form)
if err == nil {
if utils.IsHTMX(c) {
utils.HTMXRedirect(c, "/")
return c.NoContent(http.StatusNoContent)
}
return c.Redirect(http.StatusFound, "/")
}
form.Message = UserErrors.Get(err)
if form.Message == "" {
return err
}
}
return tpl.Register(form).
Render(c.Request().Context(), c.Response())
}
func (h *Handler) doRegister(c echo.Context, form *tpl.RegisterForm) error {
u, err := h.user.Register(c.Request().Context(), form)
if err != nil {
return err
}
return utils.SetUser(c, u, oneyear)
}

21
pkg/middleware/context.go Normal file
View file

@ -0,0 +1,21 @@
package middleware
import (
"context"
"github.com/labstack/echo/v4"
)
type ContextKey string
func Context(key ContextKey, value any) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
ctx := context.WithValue(c.Request().Context(), key, value)
r := c.Request().WithContext(ctx)
c.SetRequest(r)
return next(c)
}
}
}

View file

@ -0,0 +1,232 @@
package session
import (
"context"
"encoding/base32"
"log/slog"
"net/http"
"strings"
"time"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
"github.com/uptrace/bun"
)
const (
sessionIDLen = 32
defaultTableName = "sessions"
defaultMaxAge = 60 * 60 * 24 * 30 // 30 days
defaultPath = "/"
)
// Options for bunstore.
type Options struct {
TableName string
SkipCreateTable bool
}
// Store represent a bunstore.
type Store struct {
db *bun.DB
opts Options
Codecs []securecookie.Codec
SessionOpts *sessions.Options
}
type Model struct {
bun.BaseModel `bun:"table:sessions,alias:s"`
ID string `bun:",pk,unique"`
Data string
CreatedAt time.Time `bun:",nullzero,notnull,default:current_timestamp"`
UpdatedAt time.Time `bun:",nullzero,notnull,default:current_timestamp"`
ExpiresAt time.Time
}
type KeyPairs []string
func (k KeyPairs) ToKeys() [][]byte {
b := make([][]byte, 0, len(k))
for _, kk := range k {
b = append(b, []byte(kk))
}
return b
}
// New creates a new bunstore session.
func New(db *bun.DB, keyPairs KeyPairs) (*Store, error) {
return NewOptions(db, Options{}, keyPairs)
}
// NewOptions creates a new bunstore session with options.
func NewOptions(db *bun.DB, opts Options, keyPairs KeyPairs) (*Store, error) {
st := &Store{
db: db,
opts: opts,
Codecs: securecookie.CodecsFromPairs(keyPairs.ToKeys()...),
SessionOpts: &sessions.Options{
Path: defaultPath,
MaxAge: defaultMaxAge,
},
}
return st, nil
}
// Get returns a session for the given name after adding it to the registry.
func (st *Store) Get(r *http.Request, name string) (*sessions.Session, error) {
return sessions.GetRegistry(r).Get(st, name)
}
// New creates a session with name without adding it to the registry.
func (st *Store) New(r *http.Request, name string) (*sessions.Session, error) {
session := sessions.NewSession(st, name)
opts := *st.SessionOpts
session.Options = &opts
session.IsNew = true
st.MaxAge(st.SessionOpts.MaxAge)
// try fetch from db if there is a cookie
s := st.getSessionFromCookie(r, session.Name())
if s != nil {
if err := securecookie.DecodeMulti(session.Name(), s.Data, &session.Values, st.Codecs...); err != nil {
//nolint:nilerr
return session, nil
}
session.ID = s.ID
session.IsNew = false
}
return session, nil
}
// Save session and set cookie header.
func (st *Store) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error {
s := st.getSessionFromCookie(r, session.Name())
// delete if max age is < 0
if session.Options.MaxAge < 0 {
if s != nil {
if _, err := st.db.NewDelete().Model(&Model{ID: session.ID}).WherePK("id").Exec(r.Context()); err != nil {
return err
}
}
http.SetCookie(w, sessions.NewCookie(session.Name(), "", session.Options))
return nil
}
data, err := securecookie.EncodeMulti(session.Name(), session.Values, st.Codecs...)
if err != nil {
return err
}
now := time.Now()
expire := now.Add(time.Second * time.Duration(session.Options.MaxAge))
if s == nil {
// generate random session ID key suitable for storage in the db
session.ID = strings.TrimRight(
base32.StdEncoding.EncodeToString(
securecookie.GenerateRandomKey(sessionIDLen)), "=")
s = &Model{
ID: session.ID,
Data: data,
ExpiresAt: expire,
}
if _, err := st.db.NewInsert().Model(s).Exec(r.Context()); err != nil {
return err
}
} else {
s.Data = data
s.ExpiresAt = expire
if _, err := st.db.NewUpdate().Model(s).WherePK("id").Column("data", "expires_at").Exec(r.Context()); err != nil {
return err
}
}
// set session id cookie
id, err := securecookie.EncodeMulti(session.Name(), s.ID, st.Codecs...)
if err != nil {
return err
}
http.SetCookie(w, sessions.NewCookie(session.Name(), id, session.Options))
return nil
}
// getSessionFromCookie looks for an existing bunSession from a session ID stored inside a cookie.
func (st *Store) getSessionFromCookie(r *http.Request, name string) *Model {
if cookie, err := r.Cookie(name); err == nil {
sessionID := ""
if err := securecookie.DecodeMulti(name, cookie.Value, &sessionID, st.Codecs...); err != nil {
return nil
}
s := &Model{}
if err := st.db.NewSelect().
Model(s).
Where("id = ? AND expires_at > ?", sessionID, time.Now()).
Scan(r.Context()); err != nil {
return nil
}
return s
}
return nil
}
// MaxAge sets the maximum age for the store and the underlying cookie
// implementation. Individual sessions can be deleted by setting
// Options.MaxAge = -1 for that session.
func (st *Store) MaxAge(age int) {
st.SessionOpts.MaxAge = age
for _, codec := range st.Codecs {
if sc, ok := codec.(*securecookie.SecureCookie); ok {
sc.MaxAge(age)
}
}
}
// MaxLength restricts the maximum length of new sessions to l.
// If l is 0 there is no limit to the size of a session, use with caution.
// The default is 4096 (default for securecookie).
func (st *Store) MaxLength(l int) {
for _, c := range st.Codecs {
if codec, ok := c.(*securecookie.SecureCookie); ok {
codec.MaxLength(l)
}
}
}
// Cleanup deletes expired sessions.
func (st *Store) Cleanup() {
_, err := st.db.NewDelete().Model(&Model{}).Where("expires_at <= ?", time.Now()).Exec(context.Background())
if err != nil {
slog.Default().With("error", err).Error("cleanup")
}
}
// PeriodicCleanup runs Cleanup every interval. Close quit channel to stop.
func (st *Store) PeriodicCleanup(interval time.Duration, quit <-chan struct{}) {
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-t.C:
st.Cleanup()
case <-quit:
return
}
}
}

28
pkg/middleware/user.go Normal file
View file

@ -0,0 +1,28 @@
package middleware
import (
"context"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
)
func User() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
sess, err := session.Get("user", c)
if err != nil {
return err
}
u := sess.Values["user"]
c.Set("user", u)
ctx := context.WithValue(c.Request().Context(), ContextKey("user"), u)
r := c.Request().WithContext(ctx)
c.SetRequest(r)
return next(c)
}
}
}

26
pkg/model/user.go Normal file
View file

@ -0,0 +1,26 @@
package model
import (
"encoding/gob"
"encoding/json"
"time"
"github.com/uptrace/bun"
)
//nolint:gochecknoinits
func init() {
gob.Register(User{})
}
type User struct {
bun.BaseModel `bun:"table:users,alias:u"`
ID int64 `bun:",pk,autoincrement"`
Email string `bun:",notnull,unique"`
Username string `bun:",notnull,unique"`
Password string `bun:",notnull"`
Meta json.RawMessage `bun:",type:jsonb"`
CreatedAt time.Time `bun:",nullzero,notnull,default:current_timestamp"`
DeletedAt time.Time `bun:",soft_delete,nullzero"`
}

87
pkg/service/crud/crud.go Normal file
View file

@ -0,0 +1,87 @@
package crud
import (
"context"
"errors"
"github.com/uptrace/bun"
"github.com/uptrace/bun/driver/pgdriver"
)
var ErrRecordAlreadyExists = errors.New("record already exists")
type Service[T any] struct {
db *bun.DB
}
func NewService[T any](db *bun.DB) *Service[T] {
return &Service[T]{
db: db,
}
}
func (s *Service[T]) Insert(ctx context.Context, model *T) error {
if _, err := s.db.NewInsert().Model(model).Returning("*").Exec(ctx); err != nil {
pqErr := pgdriver.Error{}
if errors.As(err, &pqErr) {
if pqErr.Field('C') == "23505" {
return ErrRecordAlreadyExists
}
}
return err
}
return nil
}
func (s *Service[T]) UpdatePk(ctx context.Context, model *T, columns []string) error {
if _, err := s.db.NewUpdate().Model(model).WherePK(columns...).Column(columns...).Exec(ctx); err != nil {
pqErr := pgdriver.Error{}
if errors.As(err, &pqErr) {
if pqErr.Field('C') == "23505" {
return ErrRecordAlreadyExists
}
}
return err
}
return nil
}
//nolint:revive
func (s *Service[T]) Update(ctx context.Context, model *T, columns []string, query string, args ...any) error {
if _, err := s.db.NewUpdate().Model(model).Where(query, args...).Column(columns...).Exec(ctx); err != nil {
pqErr := pgdriver.Error{}
if errors.As(err, &pqErr) {
if pqErr.Field('C') == "23505" {
return ErrRecordAlreadyExists
}
}
return err
}
return nil
}
func (s *Service[T]) FindOne(ctx context.Context, query string, args ...any) (*T, error) {
m := new(T)
return m, s.db.NewSelect().Model(m).Where(query, args...).Scan(ctx, m)
}
//nolint:revive
func (s *Service[T]) Find(ctx context.Context, query string, args ...any) ([]T, int, error) {
m := make([]T, 0)
c, err := s.db.NewSelect().Model(m).Where(query, args...).ScanAndCount(ctx, &m)
return m, c, err
}
func (s *Service[T]) Delete(ctx context.Context, query string, args ...any) error {
_, err := s.db.NewDelete().Model((*T)(nil)).Where(query, args...).Exec(ctx)
return err
}

31
pkg/service/user/login.go Normal file
View file

@ -0,0 +1,31 @@
package user
import (
"context"
"errors"
normalizer "github.com/dimuska139/go-email-normalizer/v3"
"golang.org/x/crypto/bcrypt"
"go.neonxp.ru/framework/pkg/model"
"go.neonxp.ru/framework/pkg/tpl"
)
var ErrInvalidUserOrPassword = errors.New("invalid_user_or_password")
func (s *Service) Login(ctx context.Context, form *tpl.LoginForm) (*model.User, error) {
n := normalizer.NewNormalizer()
u := &model.User{
Email: n.Normalize(form.Email),
}
if err := s.db.NewSelect().Model(u).Where("email = ?", u.Email).Scan(ctx, u); err != nil {
return nil, errors.Join(err, ErrInvalidUserOrPassword)
}
if err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(form.Password)); err != nil {
return nil, errors.Join(err, ErrInvalidUserOrPassword)
}
return u, nil
}

View file

@ -0,0 +1,85 @@
package user
import (
"context"
"errors"
"regexp"
normalizer "github.com/dimuska139/go-email-normalizer/v3"
"github.com/uptrace/bun/driver/pgdriver"
"golang.org/x/crypto/bcrypt"
"go.neonxp.ru/framework/pkg/model"
"go.neonxp.ru/framework/pkg/tpl"
)
var (
ErrUsernameToShort = errors.New("username_to_short")
ErrUserAlreadyExist = errors.New("user_already_exists")
ErrPasswordTooWeak = errors.New("password_too_weak")
ErrPasswordTooShort = errors.New("password_too_short")
)
const (
minUsernameLen = 3
minPasswordLen = 8
)
func (s *Service) Register(ctx context.Context, form *tpl.RegisterForm) (*model.User, error) {
if len(form.Username) < minUsernameLen {
return nil, ErrUsernameToShort
}
if err := checkPasswordLever(form.Password); err != nil {
return nil, err
}
password, err := bcrypt.GenerateFromPassword([]byte(form.Password), bcrypt.DefaultCost)
if err != nil {
return nil, err
}
n := normalizer.NewNormalizer()
u := &model.User{
Username: form.Username,
Email: n.Normalize(form.Email),
Password: string(password),
}
if _, err := s.db.NewInsert().Model(u).Returning("*").Exec(ctx); err != nil {
pqErr := pgdriver.Error{}
if errors.As(err, &pqErr) {
if pqErr.Field('C') == "23505" {
return nil, ErrUserAlreadyExist
}
}
return nil, err
}
return u, nil
}
func checkPasswordLever(ps string) error {
if len(ps) < minPasswordLen {
return ErrPasswordTooShort
}
lowerCase := `[a-z]{1}`
upperCase := `[A-Z]{1}`
symbol := `[0-9!@#~$%^&*()+|_]{1}`
if b, err := regexp.MatchString(lowerCase, ps); !b || err != nil {
return ErrPasswordTooWeak
}
if b, err := regexp.MatchString(upperCase, ps); !b || err != nil {
return ErrPasswordTooWeak
}
if b, err := regexp.MatchString(symbol, ps); !b || err != nil {
return ErrPasswordTooWeak
}
return nil
}

12
pkg/service/user/user.go Normal file
View file

@ -0,0 +1,12 @@
package user
import "github.com/uptrace/bun"
type Service struct {
db *bun.DB
}
// NewService returns new Service.
func NewService(db *bun.DB) *Service {
return &Service{db: db}
}

10
pkg/tpl/error.templ Normal file
View file

@ -0,0 +1,10 @@
package tpl
import "strconv"
templ ErrorPage(code int, message string) {
@Layout() {
<h1>Ошибка { strconv.Itoa(code) }!</h1>
<p>{ message }</p>
}
}

86
pkg/tpl/error_templ.go Normal file
View file

@ -0,0 +1,86 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.2.778
package tpl
//lint:file-ignore SA4006 This context is only used if a nested component is present.
import "github.com/a-h/templ"
import templruntime "github.com/a-h/templ/runtime"
import "strconv"
func ErrorPage(code int, message string) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var1 := templ.GetChildren(ctx)
if templ_7745c5c3_Var1 == nil {
templ_7745c5c3_Var1 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Var2 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 1)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(strconv.Itoa(code))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `pkg/tpl/error.templ`, Line: 7, Col: 39}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 2)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(message)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `pkg/tpl/error.templ`, Line: 8, Col: 14}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 3)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return templ_7745c5c3_Err
})
templ_7745c5c3_Err = Layout().Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return templ_7745c5c3_Err
})
}
var _ = templruntime.GeneratedTemplate

3
pkg/tpl/error_templ.txt Normal file
View file

@ -0,0 +1,3 @@
<h1>Ошибка
!</h1><p>
</p>

49
pkg/tpl/layout.templ Normal file
View file

@ -0,0 +1,49 @@
package tpl
import "go.neonxp.ru/framework/pkg/utils"
templ Layout() {
{{ user := utils.GetUserCtx(ctx) }}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="color-scheme" content="light dark"/>
<link rel="stylesheet" href="/css/pico/pico.blue.min.css"/>
<link rel="stylesheet" href="/css/style.css"/>
<link rel="stylesheet" href="/css/fork-awesome.min.css"/>
<title>App</title>
</head>
<body>
<main class="container">
<nav>
<ul>
<li><a href="/"><strong>App</strong></a></li>
<li><span aria-busy="true" id="loader" class="htmx-indicator">Загрузка...</span></li>
</ul>
<ul hx-boost="true" hx-indicator="#loader">
if user == nil {
<li><a href="/user/login">Вход</a></li>
<li><a href="/user/register">Регистрация</a></li>
} else {
<li><a href="/user/profile">{ user.Username }</a></li>
<li><a href="#" hx-post="/user/logout">Выход</a></li>
}
</ul>
</nav>
{ children... }
</main>
</body>
<footer>
<main class="container">
<nav>
<ul>
<li>Сделал <a href="https://neonxp.ru/">NeonXP</a> в 2024 году.</li>
</ul>
</nav>
</main>
</footer>
<script src="/js/htmx.min.js"></script>
</html>
}

79
pkg/tpl/layout_templ.go Normal file
View file

@ -0,0 +1,79 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.2.778
package tpl
//lint:file-ignore SA4006 This context is only used if a nested component is present.
import "github.com/a-h/templ"
import templruntime "github.com/a-h/templ/runtime"
import "go.neonxp.ru/framework/pkg/utils"
func Layout() templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var1 := templ.GetChildren(ctx)
if templ_7745c5c3_Var1 == nil {
templ_7745c5c3_Var1 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
user := utils.GetUserCtx(ctx)
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 1)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if user == nil {
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 2)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} else {
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 3)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(user.Username)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `pkg/tpl/layout.templ`, Line: 30, Col: 50}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 4)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 5)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templ_7745c5c3_Var1.Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 6)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return templ_7745c5c3_Err
})
}
var _ = templruntime.GeneratedTemplate

6
pkg/tpl/layout_templ.txt Normal file
View file

@ -0,0 +1,6 @@
<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><meta name=\"color-scheme\" content=\"light dark\"><link rel=\"stylesheet\" href=\"/css/pico/pico.blue.min.css\"><link rel=\"stylesheet\" href=\"/css/style.css\"><link rel=\"stylesheet\" href=\"/css/fork-awesome.min.css\"><title>App</title></head><body><main class=\"container\"><nav><ul><li><a href=\"/\"><strong>App</strong></a></li><li><span aria-busy=\"true\" id=\"loader\" class=\"htmx-indicator\">Загрузка...</span></li></ul><ul hx-boost=\"true\" hx-indicator=\"#loader\">
<li><a href=\"/user/login\">Вход</a></li><li><a href=\"/user/register\">Регистрация</a></li>
<li><a href=\"/user/profile\">
</a></li><li><a href=\"#\" hx-post=\"/user/logout\">Выход</a></li>
</ul></nav>
</main></body><footer><main class=\"container\"><nav><ul><li>Сделал <a href=\"https://neonxp.ru/\">NeonXP</a> в 2024 году.</li></ul></nav></main></footer><script src=\"/js/htmx.min.js\"></script></html>

60
pkg/tpl/login.templ Normal file
View file

@ -0,0 +1,60 @@
package tpl
templ Login(form *LoginForm) {
@Layout() {
<article class="grid">
<div>
<hgroup>
<h1>Вход</h1>
<p>Вход в систему</p>
</hgroup>
<form
method="post"
hx-post="/user/login"
hx-target="form"
hx-select="form"
hx-indicator="#loader"
>
if form.Message != "" {
<article>
<header>Ошибка</header>
{ form.Message }
</article>
}
<input
type="email"
name="email"
placeholder="Электропочта"
aria-label="Электропочта"
autocomplete="email"
value={ form.Email }
required
/>
<input
type="password"
name="password"
placeholder="Пароль"
aria-label="Пароль"
autocomplete="current-password"
required
/>
<fieldset>
<label for="remember">
<input type="checkbox" role="switch" id="remember" name="remember" checked={ form.Remember }/>
Запомнить
</label>
</fieldset>
<button type="submit" class="contrast">Вход</button>
</form>
</div>
<div></div>
</article>
}
}
type LoginForm struct {
Message string
Email string `form:"email"`
Password string `form:"password"`
Remember string `form:"remember"`
}

114
pkg/tpl/login_templ.go Normal file
View file

@ -0,0 +1,114 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.2.778
package tpl
//lint:file-ignore SA4006 This context is only used if a nested component is present.
import "github.com/a-h/templ"
import templruntime "github.com/a-h/templ/runtime"
func Login(form *LoginForm) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var1 := templ.GetChildren(ctx)
if templ_7745c5c3_Var1 == nil {
templ_7745c5c3_Var1 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Var2 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 1)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if form.Message != "" {
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 2)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(form.Message)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `pkg/tpl/login.templ`, Line: 21, Col: 21}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 3)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 4)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(form.Email)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `pkg/tpl/login.templ`, Line: 30, Col: 24}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 5)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(form.Remember)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `pkg/tpl/login.templ`, Line: 43, Col: 97}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 6)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return templ_7745c5c3_Err
})
templ_7745c5c3_Err = Layout().Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return templ_7745c5c3_Err
})
}
type LoginForm struct {
Message string
Email string `form:"email"`
Password string `form:"password"`
Remember string `form:"remember"`
}
var _ = templruntime.GeneratedTemplate

6
pkg/tpl/login_templ.txt Normal file
View file

@ -0,0 +1,6 @@
<article class=\"grid\"><div><hgroup><h1>Вход</h1><p>Вход в систему</p></hgroup><form method=\"post\" hx-post=\"/user/login\" hx-target=\"form\" hx-select=\"form\" hx-indicator=\"#loader\">
<article><header>Ошибка</header>
</article>
<input type=\"email\" name=\"email\" placeholder=\"Электропочта\" aria-label=\"Электропочта\" autocomplete=\"email\" value=\"
\" required> <input type=\"password\" name=\"password\" placeholder=\"Пароль\" aria-label=\"Пароль\" autocomplete=\"current-password\" required><fieldset><label for=\"remember\"><input type=\"checkbox\" role=\"switch\" id=\"remember\" name=\"remember\" checked=\"
\"> Запомнить</label></fieldset><button type=\"submit\" class=\"contrast\">Вход</button></form></div><div></div></article>

17
pkg/tpl/profile.templ Normal file
View file

@ -0,0 +1,17 @@
package tpl
import "go.neonxp.ru/framework/pkg/model"
templ Profile(user *model.User) {
@Layout() {
<article class="grid">
<div>
<hgroup>
<h1>{ user.Username }</h1>
<p>{ user.Email }</p>
</hgroup>
</div>
<div></div>
</article>
}
}

86
pkg/tpl/profile_templ.go Normal file
View file

@ -0,0 +1,86 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.2.778
package tpl
//lint:file-ignore SA4006 This context is only used if a nested component is present.
import "github.com/a-h/templ"
import templruntime "github.com/a-h/templ/runtime"
import "go.neonxp.ru/framework/pkg/model"
func Profile(user *model.User) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var1 := templ.GetChildren(ctx)
if templ_7745c5c3_Var1 == nil {
templ_7745c5c3_Var1 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Var2 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 1)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(user.Username)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `pkg/tpl/profile.templ`, Line: 10, Col: 24}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 2)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(user.Email)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `pkg/tpl/profile.templ`, Line: 11, Col: 20}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 3)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return templ_7745c5c3_Err
})
templ_7745c5c3_Err = Layout().Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return templ_7745c5c3_Err
})
}
var _ = templruntime.GeneratedTemplate

View file

@ -0,0 +1,3 @@
<article class=\"grid\"><div><hgroup><h1>
</h1><p>
</p></hgroup></div><div></div></article>

63
pkg/tpl/register.templ Normal file
View file

@ -0,0 +1,63 @@
package tpl
templ Register(form *RegisterForm) {
@Layout() {
<article class="grid">
<div>
<hgroup>
<h1>Регистрация</h1>
<p>Регистрация в системе</p>
</hgroup>
<form
method="post"
hx-post="/user/register"
hx-target="form"
hx-select="form"
hx-indicator="#loader"
>
if form.Message != "" {
<article>
<header>Ошибка</header>
{ form.Message }
</article>
}
<input
type="text"
name="username"
placeholder="Отображаемое имя"
aria-label="Отображаемое имя"
autocomplete="username"
value={ form.Username }
required
/>
<input
type="email"
name="email"
placeholder="Электропочта"
aria-label="Электропочта"
autocomplete="email"
value={ form.Email }
required
/>
<input
type="password"
name="password"
placeholder="Пароль"
aria-label="Пароль"
autocomplete="current-password"
required
/>
<button type="submit" class="contrast">Регистрация</button>
</form>
</div>
<div></div>
</article>
}
}
type RegisterForm struct {
Message string
Username string `form:"username"`
Email string `form:"email"`
Password string `form:"password"`
}

114
pkg/tpl/register_templ.go Normal file
View file

@ -0,0 +1,114 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.2.778
package tpl
//lint:file-ignore SA4006 This context is only used if a nested component is present.
import "github.com/a-h/templ"
import templruntime "github.com/a-h/templ/runtime"
func Register(form *RegisterForm) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Var1 := templ.GetChildren(ctx)
if templ_7745c5c3_Var1 == nil {
templ_7745c5c3_Var1 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Var2 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 1)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if form.Message != "" {
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 2)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(form.Message)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `pkg/tpl/register.templ`, Line: 21, Col: 21}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 3)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 4)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(form.Username)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `pkg/tpl/register.templ`, Line: 30, Col: 27}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 5)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(form.Email)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `pkg/tpl/register.templ`, Line: 39, Col: 24}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templ.WriteWatchModeString(templ_7745c5c3_Buffer, 6)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return templ_7745c5c3_Err
})
templ_7745c5c3_Err = Layout().Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return templ_7745c5c3_Err
})
}
type RegisterForm struct {
Message string
Username string `form:"username"`
Email string `form:"email"`
Password string `form:"password"`
}
var _ = templruntime.GeneratedTemplate

View file

@ -0,0 +1,6 @@
<article class=\"grid\"><div><hgroup><h1>Регистрация</h1><p>Регистрация в системе</p></hgroup><form method=\"post\" hx-post=\"/user/register\" hx-target=\"form\" hx-select=\"form\" hx-indicator=\"#loader\">
<article><header>Ошибка</header>
</article>
<input type=\"text\" name=\"username\" placeholder=\"Отображаемое имя\" aria-label=\"Отображаемое имя\" autocomplete=\"username\" value=\"
\" required> <input type=\"email\" name=\"email\" placeholder=\"Электропочта\" aria-label=\"Электропочта\" autocomplete=\"email\" value=\"
\" required> <input type=\"password\" name=\"password\" placeholder=\"Пароль\" aria-label=\"Пароль\" autocomplete=\"current-password\" required> <button type=\"submit\" class=\"contrast\">Регистрация</button></form></div><div></div></article>

11
pkg/utils/htmx.go Normal file
View file

@ -0,0 +1,11 @@
package utils
import "github.com/labstack/echo/v4"
func IsHTMX(c echo.Context) bool {
return c.Request().Header.Get("HX-Request") == "true"
}
func HTMXRedirect(c echo.Context, location string) {
c.Response().Header().Set("HX-Redirect", location)
}

41
pkg/utils/user.go Normal file
View file

@ -0,0 +1,41 @@
package utils
import (
"context"
"github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
"go.neonxp.ru/framework/pkg/middleware"
"go.neonxp.ru/framework/pkg/model"
)
func GetUserCtx(ctx context.Context) *model.User {
u := ctx.Value(middleware.ContextKey("user"))
if u == nil {
return nil
}
if u, ok := u.(model.User); ok {
return &u
}
return nil
}
func SetUser(c echo.Context, u *model.User, maxage int) error {
sess, err := session.Get("user", c)
if err != nil {
return err
}
sess.Values["user"] = u
sess.Options = &sessions.Options{
Path: "/",
MaxAge: maxage,
HttpOnly: true,
Secure: true,
}
return sess.Save(c.Request(), c.Response())
}

1
static/css/flexboxgrid.min.css vendored Normal file

File diff suppressed because one or more lines are too long

12
static/css/fork-awesome.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.amber.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.blue.min.css vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

4
static/css/pico/pico.colors.min.css vendored Normal file

File diff suppressed because one or more lines are too long

2802
static/css/pico/pico.css Normal file

File diff suppressed because it is too large Load diff

4
static/css/pico/pico.cyan.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.fuchsia.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.green.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.grey.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.indigo.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.jade.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.lime.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.orange.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.pink.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.pumpkin.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.purple.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.red.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.sand.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.slate.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.violet.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.yellow.min.css vendored Normal file

File diff suppressed because one or more lines are too long

4
static/css/pico/pico.zinc.min.css vendored Normal file

File diff suppressed because one or more lines are too long

36
static/css/style.css Normal file
View file

@ -0,0 +1,36 @@
.captcha {
height: 65px;
}
article header {
display: flex;
flex-direction: row;
justify-content: space-between;
}
article footer {
display: flex;
flex-direction: row;
justify-content: space-between;
}
.htmx-indicator{
opacity:0;
transition: opacity 500ms ease-in;
}
.htmx-request .htmx-indicator{
opacity:1;
}
.htmx-request.htmx-indicator{
opacity:1;
}
.header {
display: flex;
flex-direction: row;
justify-content: space-between;
margin-bottom: var(--pico-block-spacing-vertical);
}
.top-menu {
text-align: end;
}

Binary file not shown.

File diff suppressed because it is too large Load diff

After

Width:  |  Height:  |  Size: 547 KiB

Binary file not shown.

Binary file not shown.

Binary file not shown.

6
static/fs.go Normal file
View file

@ -0,0 +1,6 @@
package static
import "embed"
//go:embed *
var FS embed.FS

9
static/js/ext/README.md Normal file
View file

@ -0,0 +1,9 @@
# Why Are These Files Here?
These are legacy extensions for htmx 1.x and are **NOT** actively maintained or guaranteed to work with htmx 2.x.
They are here because we unfortunately linked to unversioned unpkg URLs in the installation guides for them
in 1.x, so we need to keep them here to preserve those URLs and not break existing users functionality.
If you are looking for extensions for htmx 2.x, please see the [htmx 2.0 extensions site](https://htmx.org/extensions),
which has links to the new extensions repos (They have all been moved to their own NPM projects and URLs, like
they should have been from the start!)

View file

@ -0,0 +1,5 @@
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! THESE FILES ARE DEPRECATED AND UNSUPPORTED !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
SEE README.md FOR MORE DETAILS

View file

@ -0,0 +1,11 @@
if (htmx.version && !htmx.version.startsWith("1.")) {
console.warn("WARNING: You are using an htmx 1 extension with htmx " + htmx.version +
". It is recommended that you move to the version of this extension found on https://htmx.org/extensions")
}
htmx.defineExtension('ajax-header', {
onEvent: function (name, evt) {
if (name === "htmx:configRequest") {
evt.detail.headers['X-Requested-With'] = 'XMLHttpRequest';
}
}
});

View file

@ -0,0 +1,20 @@
if (htmx.version && !htmx.version.startsWith("1.")) {
console.warn("WARNING: You are using an htmx 1 extension with htmx " + htmx.version +
". It is recommended that you move to the version of this extension found on https://htmx.org/extensions")
}
htmx.defineExtension('alpine-morph', {
isInlineSwap: function (swapStyle) {
return swapStyle === 'morph';
},
handleSwap: function (swapStyle, target, fragment) {
if (swapStyle === 'morph') {
if (fragment.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
Alpine.morph(target, fragment.firstElementChild);
return [target];
} else {
Alpine.morph(target, fragment.outerHTML);
return [target];
}
}
}
});

View file

@ -0,0 +1,97 @@
(function () {
if (htmx.version && !htmx.version.startsWith("1.")) {
console.warn("WARNING: You are using an htmx 1 extension with htmx " + htmx.version +
". It is recommended that you move to the version of this extension found on https://htmx.org/extensions")
}
function splitOnWhitespace(trigger) {
return trigger.split(/\s+/);
}
function parseClassOperation(trimmedValue) {
var split = splitOnWhitespace(trimmedValue);
if (split.length > 1) {
var operation = split[0];
var classDef = split[1].trim();
var cssClass;
var delay;
if (classDef.indexOf(":") > 0) {
var splitCssClass = classDef.split(':');
cssClass = splitCssClass[0];
delay = htmx.parseInterval(splitCssClass[1]);
} else {
cssClass = classDef;
delay = 100;
}
return {
operation: operation,
cssClass: cssClass,
delay: delay
}
} else {
return null;
}
}
function performOperation(elt, classOperation, classList, currentRunTime) {
setTimeout(function () {
elt.classList[classOperation.operation].call(elt.classList, classOperation.cssClass);
}, currentRunTime)
}
function toggleOperation(elt, classOperation, classList, currentRunTime) {
setTimeout(function () {
setInterval(function () {
elt.classList[classOperation.operation].call(elt.classList, classOperation.cssClass);
}, classOperation.delay);
}, currentRunTime)
}
function processClassList(elt, classList) {
var runs = classList.split("&");
for (var i = 0; i < runs.length; i++) {
var run = runs[i];
var currentRunTime = 0;
var classOperations = run.split(",");
for (var j = 0; j < classOperations.length; j++) {
var value = classOperations[j];
var trimmedValue = value.trim();
var classOperation = parseClassOperation(trimmedValue);
if (classOperation) {
if (classOperation.operation === "toggle") {
toggleOperation(elt, classOperation, classList, currentRunTime);
currentRunTime = currentRunTime + classOperation.delay;
} else {
currentRunTime = currentRunTime + classOperation.delay;
performOperation(elt, classOperation, classList, currentRunTime);
}
}
}
}
}
function maybeProcessClasses(elt) {
if (elt.getAttribute) {
var classList = elt.getAttribute("classes") || elt.getAttribute("data-classes");
if (classList) {
processClassList(elt, classList);
}
}
}
htmx.defineExtension('class-tools', {
onEvent: function (name, evt) {
if (name === "htmx:afterProcessNode") {
var elt = evt.detail.elt;
maybeProcessClasses(elt);
if (elt.querySelectorAll) {
var children = elt.querySelectorAll("[classes], [data-classes]");
for (var i = 0; i < children.length; i++) {
maybeProcessClasses(children[i]);
}
}
}
}
});
})();

View file

@ -0,0 +1,100 @@
if (htmx.version && !htmx.version.startsWith("1.")) {
console.warn("WARNING: You are using an htmx 1 extension with htmx " + htmx.version +
". It is recommended that you move to the version of this extension found on https://htmx.org/extensions")
}
htmx.defineExtension('client-side-templates', {
transformResponse : function(text, xhr, elt) {
var mustacheTemplate = htmx.closest(elt, "[mustache-template]");
if (mustacheTemplate) {
var data = JSON.parse(text);
var templateId = mustacheTemplate.getAttribute('mustache-template');
var template = htmx.find("#" + templateId);
if (template) {
return Mustache.render(template.innerHTML, data);
} else {
throw "Unknown mustache template: " + templateId;
}
}
var mustacheArrayTemplate = htmx.closest(elt, "[mustache-array-template]");
if (mustacheArrayTemplate) {
var data = JSON.parse(text);
var templateId = mustacheArrayTemplate.getAttribute('mustache-array-template');
var template = htmx.find("#" + templateId);
if (template) {
return Mustache.render(template.innerHTML, {"data": data });
} else {
throw "Unknown mustache template: " + templateId;
}
}
var handlebarsTemplate = htmx.closest(elt, "[handlebars-template]");
if (handlebarsTemplate) {
var data = JSON.parse(text);
var templateId = handlebarsTemplate.getAttribute('handlebars-template');
var templateElement = htmx.find('#' + templateId).innerHTML;
var renderTemplate = Handlebars.compile(templateElement);
if (renderTemplate) {
return renderTemplate(data);
} else {
throw "Unknown handlebars template: " + templateId;
}
}
var handlebarsArrayTemplate = htmx.closest(elt, "[handlebars-array-template]");
if (handlebarsArrayTemplate) {
var data = JSON.parse(text);
var templateId = handlebarsArrayTemplate.getAttribute('handlebars-array-template');
var templateElement = htmx.find('#' + templateId).innerHTML;
var renderTemplate = Handlebars.compile(templateElement);
if (renderTemplate) {
return renderTemplate(data);
} else {
throw "Unknown handlebars template: " + templateId;
}
}
var nunjucksTemplate = htmx.closest(elt, "[nunjucks-template]");
if (nunjucksTemplate) {
var data = JSON.parse(text);
var templateName = nunjucksTemplate.getAttribute('nunjucks-template');
var template = htmx.find('#' + templateName);
if (template) {
return nunjucks.renderString(template.innerHTML, data);
} else {
return nunjucks.render(templateName, data);
}
}
var xsltTemplate = htmx.closest(elt, "[xslt-template]");
if (xsltTemplate) {
var templateId = xsltTemplate.getAttribute('xslt-template');
var template = htmx.find("#" + templateId);
if (template) {
var content = template.innerHTML ? new DOMParser().parseFromString(template.innerHTML, 'application/xml')
: template.contentDocument;
var processor = new XSLTProcessor();
processor.importStylesheet(content);
var data = new DOMParser().parseFromString(text, "application/xml");
var frag = processor.transformToFragment(data, document);
return new XMLSerializer().serializeToString(frag);
} else {
throw "Unknown XSLT template: " + templateId;
}
}
var nunjucksArrayTemplate = htmx.closest(elt, "[nunjucks-array-template]");
if (nunjucksArrayTemplate) {
var data = JSON.parse(text);
var templateName = nunjucksArrayTemplate.getAttribute('nunjucks-array-template');
var template = htmx.find('#' + templateName);
if (template) {
return nunjucks.renderString(template.innerHTML, {"data": data});
} else {
return nunjucks.render(templateName, {"data": data});
}
}
return text;
}
});

15
static/js/ext/debug.js Normal file
View file

@ -0,0 +1,15 @@
if (htmx.version && !htmx.version.startsWith("1.")) {
console.warn("WARNING: You are using an htmx 1 extension with htmx " + htmx.version +
". It is recommended that you move to the version of this extension found on https://htmx.org/extensions")
}
htmx.defineExtension('debug', {
onEvent: function (name, evt) {
if (console.debug) {
console.debug(name, evt);
} else if (console) {
console.log("DEBUG:", name, evt);
} else {
throw "NO CONSOLE SUPPORTED"
}
}
});

View file

@ -0,0 +1,20 @@
if (htmx.version && !htmx.version.startsWith("1.")) {
console.warn("WARNING: You are using an htmx 1 extension with htmx " + htmx.version +
". It is recommended that you move to the version of this extension found on https://htmx.org/extensions")
}
// Disable Submit Button
htmx.defineExtension('disable-element', {
onEvent: function (name, evt) {
let elt = evt.detail.elt;
let target = elt.getAttribute("hx-disable-element");
let targetElements = (target == "self") ? [ elt ] : document.querySelectorAll(target);
for (var i = 0; i < targetElements.length; i++) {
if (name === "htmx:beforeRequest" && targetElements[i]) {
targetElements[i].disabled = true;
} else if (name == "htmx:afterRequest" && targetElements[i]) {
targetElements[i].disabled = false;
}
}
}
});

Some files were not shown because too many files have changed in this diff Show more