fixed
This commit is contained in:
1
backend
1
backend
Submodule backend deleted from b5703172c8
BIN
backend/.DS_Store
vendored
Normal file
BIN
backend/.DS_Store
vendored
Normal file
Binary file not shown.
8
backend/.idea/.gitignore
generated
vendored
Executable file
8
backend/.idea/.gitignore
generated
vendored
Executable file
@@ -0,0 +1,8 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
6
backend/.idea/vcs.xml
generated
Executable file
6
backend/.idea/vcs.xml
generated
Executable file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
31
backend/Dockerfile
Executable file
31
backend/Dockerfile
Executable file
@@ -0,0 +1,31 @@
|
||||
#!/bin/ash
|
||||
# Specifies a parent image
|
||||
FROM golang:1.26.4-alpine AS builder
|
||||
|
||||
# Creates an app directory to hold your app’s source code
|
||||
WORKDIR /build
|
||||
|
||||
# Installs Go dependencies
|
||||
COPY go.mod ./
|
||||
COPY go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY . .
|
||||
|
||||
# Builds your app with optional configuration
|
||||
RUN GOARCH=amd64 GOOS=linux go build -o myapp ./app.go
|
||||
|
||||
FROM scratch
|
||||
|
||||
WORKDIR /app/
|
||||
|
||||
COPY --from=builder /build/myapp .
|
||||
COPY --from=builder /build/config.yaml .
|
||||
COPY --from=builder /build/web ./web
|
||||
|
||||
# Tells Docker which network port your container listens on
|
||||
EXPOSE 5050
|
||||
#ENTRYPOINT ["/app/myapp"]
|
||||
CMD ["/app/myapp"]
|
||||
|
||||
|
||||
27
backend/Makefile
Executable file
27
backend/Makefile
Executable file
@@ -0,0 +1,27 @@
|
||||
# Dependencies
|
||||
dependencies:
|
||||
docker-compose -f ./deployment/dependencies/docker-compose.yaml up -d
|
||||
|
||||
# Self-hosted registry + Watchtower
|
||||
registry-up:
|
||||
docker compose -f ./deployment/registry/docker-compose.yaml up -d
|
||||
registry-down:
|
||||
docker compose -f ./deployment/registry/docker-compose.yaml down
|
||||
deploy:
|
||||
./scripts/deploy.sh
|
||||
|
||||
# Database
|
||||
create-migration:
|
||||
migrate create -ext sql -dir db/migrations -tz Local init
|
||||
|
||||
# --- for Macos
|
||||
migrate:
|
||||
migrate -database 'postgres://bank_admin:bank%40%2323%23%40_password@localhost:5424/bank_db?sslmode=disable' -path db/migrations up
|
||||
migrate-rollback:
|
||||
migrate -database 'postgres://bank_admin:bank%40%2323%23%40_password@localhost:5424/bank_db?sslmode=disable' -path db/migrations down
|
||||
|
||||
# ---- for linux
|
||||
# migrate:
|
||||
# migrate -database 'postgresql://bank_admin:bank@#23#@_password@localhost:5454/bank_db?sslmode=disable' -path db/migrations up
|
||||
# migrate-rollback:
|
||||
# migrate -database 'postgresql://bank_admin:bank@#23#@_password@localhost:5454/bank_db?sslmode=disable' -path db/migrations down
|
||||
24
backend/README.md
Executable file
24
backend/README.md
Executable file
@@ -0,0 +1,24 @@
|
||||
|
||||
## Backend services of Bank line
|
||||
### Services
|
||||
This is an entry service of our application.
|
||||
This service will accept all requests and collect all required info from other services.<br/>
|
||||
Only this service will be with HTTP support.
|
||||
|
||||
[//]: # (* <b>Authorization service</b><br/>)
|
||||
|
||||
[//]: # ( This is one of the most important part of every application. In our app this is implemented as RPC service.<br/>)
|
||||
|
||||
[//]: # ( You can read more about service in documentation.)
|
||||
## Guide to run app
|
||||
### 1. Clone repo to local directory
|
||||
### 2. Make sure you have installed `Docker` and `docker-compose`
|
||||
### 2. Execute `docker compose up -d --build` in project folder
|
||||
|
||||
#### Documentation is in `docs/gateway.md`
|
||||
|
||||
## Guide to database migrations
|
||||
### Before make sure you have installed golang-migrate CLI tool.
|
||||
### 1. To create migration execute `make create-migration name='migration_name'`
|
||||
### 2. Apply migration `make migrate`
|
||||
### 3. Rollback migration `make migrate-rollback`
|
||||
73
backend/app.go
Executable file
73
backend/app.go
Executable file
@@ -0,0 +1,73 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
_ "bankline/docs"
|
||||
"bankline/internal/admin/auth"
|
||||
"bankline/internal/config"
|
||||
handlermanager "bankline/internal/handlers/manager"
|
||||
"bankline/pkg/client/postgresql"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
swaggerFiles "github.com/swaggo/files"
|
||||
ginSwagger "github.com/swaggo/gin-swagger"
|
||||
)
|
||||
|
||||
// @title Bank Service APIs
|
||||
// @version 1.0
|
||||
// @description Testing Swagger APIs.
|
||||
// @termsOfService http://swagger.io/terms/
|
||||
|
||||
// @contact.name API Support
|
||||
// @contact.url http://www.swagger.io/support
|
||||
|
||||
// @contact.email support@swagger.io
|
||||
// @license.name Apache 2.0
|
||||
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
|
||||
// @host localhost:5050
|
||||
// @BasePath /v1
|
||||
|
||||
// @securityDefinitions.apikey BearerAuth
|
||||
// @in header
|
||||
// @name Authorization
|
||||
|
||||
// @tag.name auth
|
||||
// @tag.name admin
|
||||
// @tag.name categories
|
||||
// @tag.name sub-categories
|
||||
// @tag.name settings
|
||||
|
||||
// @Success 200 {object} appresult.AppSuccess "Success Code"
|
||||
// @Failure 400 {object} appresult.AppError "Error Code"
|
||||
// @schemes http
|
||||
func main() {
|
||||
|
||||
cfg := config.GetConfig()
|
||||
logger := logging.GetLogger()
|
||||
|
||||
postgresSQLClient := startPostgresql(cfg, logger)
|
||||
start(handlermanager.Manager(postgresSQLClient, logger), cfg)
|
||||
}
|
||||
|
||||
func startPostgresql(cfg *config.Config, logger *logging.Logger) *pgxpool.Pool {
|
||||
postgresSQLClient, err := postgresql.NewClient(context.TODO(), 3, cfg.Storage)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return postgresSQLClient
|
||||
}
|
||||
|
||||
func start(router *gin.Engine, cfg *config.Config) {
|
||||
logger := logging.GetLogger()
|
||||
logger.Info("start application")
|
||||
|
||||
ginSwagger.WrapHandler(swaggerFiles.Handler,
|
||||
ginSwagger.DefaultModelsExpandDepth(-1))
|
||||
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
|
||||
router.GET("/images/:id", auth.GetObject)
|
||||
|
||||
router.Run(`:` + cfg.Listen.Port)
|
||||
|
||||
}
|
||||
15
backend/config.yaml
Executable file
15
backend/config.yaml
Executable file
@@ -0,0 +1,15 @@
|
||||
is_debug: true
|
||||
listen:
|
||||
type: port
|
||||
port: 5050
|
||||
jwt_key: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpX@VCJ9.yueyJzdWIiOiIyNTEyNzMiLCJpYXQiOjE1MTYy#MzkwMjJ9.o_LoJm03CaE6!0dugdR8sjIuFgPxGT7I2W8NvugFqHRY
|
||||
storage:
|
||||
host: main-db
|
||||
# host: localhost
|
||||
port: 5432
|
||||
database: bank_db
|
||||
username: bank_admin
|
||||
password: bank@#23#@_password
|
||||
pg_pool_max_conn: 10
|
||||
app_version: 0.0.1
|
||||
public_file_path: ./public
|
||||
BIN
backend/db/.DS_Store
vendored
Normal file
BIN
backend/db/.DS_Store
vendored
Normal file
Binary file not shown.
10
backend/db/migrations/20260702125108_init.down.sql
Normal file
10
backend/db/migrations/20260702125108_init.down.sql
Normal file
@@ -0,0 +1,10 @@
|
||||
DROP TABLE IF EXISTS sub_categories_content;
|
||||
DROP TABLE IF EXISTS news_content;
|
||||
DROP TABLE IF EXISTS sub_categories;
|
||||
DROP TABLE IF EXISTS categories;
|
||||
DROP TABLE IF EXISTS news;
|
||||
DROP TABLE IF EXISTS banner;
|
||||
DROP TABLE IF EXISTS static;
|
||||
DROP TABLE IF EXISTS currency;
|
||||
DROP TABLE IF EXISTS setting;
|
||||
DROP TABLE IF EXISTS admin;
|
||||
132
backend/db/migrations/20260702125108_init.up.sql
Normal file
132
backend/db/migrations/20260702125108_init.up.sql
Normal file
@@ -0,0 +1,132 @@
|
||||
CREATE TABLE IF NOT EXISTS admin (
|
||||
"id" bigserial primary key,
|
||||
"login" character varying(250) NOT NULL DEFAULT '',
|
||||
"password" character varying(250) NOT NULL DEFAULT '',
|
||||
"fullname" character varying(250) NOT NULL DEFAULT '',
|
||||
"username" character varying(250) NOT NULL DEFAULT '',
|
||||
"phone_number" character varying(250) NOT NULL DEFAULT '',
|
||||
"avatar" character varying(250) NOT NULL DEFAULT '',
|
||||
"social_media" json NOT NULL DEFAULT '{}'::json,
|
||||
"light_mode" integer DEFAULT 1 NOT NULL,
|
||||
"role" character varying(250) NOT NULL DEFAULT 'user',
|
||||
"updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
"created_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
INSERT INTO admin (phone_number, password, fullname, login, role)
|
||||
VALUES (
|
||||
'61531216',
|
||||
'$2a$12$k2QqAe13wQSnblm9wPCfV.215AmK6Y7rnquoUEzL/0g6ekZ2jvR2C',
|
||||
'Admin',
|
||||
'admin@admin.com',
|
||||
'admin'
|
||||
);
|
||||
-- tbbank2026
|
||||
CREATE TABLE IF NOT EXISTS categories (
|
||||
"id" bigserial primary key,
|
||||
"name" json NOT NULL DEFAULT '{}'::json,
|
||||
"status" boolean DEFAULT false NOT NULL,
|
||||
"img" character varying(250) NOT NULL DEFAULT '',
|
||||
"updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
"created_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sub_categories (
|
||||
"id" bigserial primary key,
|
||||
"category_id" int,
|
||||
"name" json NOT NULL DEFAULT '{}'::json,
|
||||
"status" boolean DEFAULT false NOT NULL,
|
||||
"count" integer DEFAULT 0 NOT NULL,
|
||||
"updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
"created_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
CONSTRAINT sub_cat_id_fk
|
||||
FOREIGN KEY ("category_id")
|
||||
REFERENCES categories("id")
|
||||
ON UPDATE CASCADE ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sub_categories_content (
|
||||
"id" bigserial primary key,
|
||||
"sub_category_id" int,
|
||||
"en" TEXT NOT NULL,
|
||||
"ru" TEXT NOT NULL,
|
||||
"tm" TEXT NOT NULL,
|
||||
"updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
"created_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
CONSTRAINT sub_categories_content_sub_category_id_key UNIQUE ("sub_category_id"),
|
||||
CONSTRAINT sub_category_id_fk
|
||||
FOREIGN KEY ("sub_category_id")
|
||||
REFERENCES sub_categories("id")
|
||||
ON UPDATE CASCADE ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS banner (
|
||||
"id" bigserial primary key,
|
||||
"title" json NOT NULL DEFAULT '{}'::json,
|
||||
"content_tm" TEXT NOT NULL DEFAULT '',
|
||||
"content_ru" TEXT NOT NULL DEFAULT '',
|
||||
"content_en" TEXT NOT NULL DEFAULT '',
|
||||
"img" character varying(250) NOT NULL,
|
||||
"updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
"created_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS setting (
|
||||
"id" bigserial primary key,
|
||||
"uuid" uuid NOT NULL DEFAULT gen_random_uuid() UNIQUE,
|
||||
"logo_r" character varying(250) NOT NULL DEFAULT '',
|
||||
"phone_number" character varying(250) NOT NULL DEFAULT '',
|
||||
"fax_number" character varying(250) NOT NULL DEFAULT '',
|
||||
"help_number" character varying(250) NOT NULL DEFAULT '',
|
||||
"updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
"created_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
INSERT INTO setting (logo_r, phone_number, fax_number, help_number)
|
||||
VALUES ('', '', '', '');
|
||||
|
||||
CREATE TABLE IF NOT EXISTS news (
|
||||
"id" bigserial primary key,
|
||||
"img" character varying(250) NOT NULL,
|
||||
"title" json NOT NULL DEFAULT '{}'::json,
|
||||
"date_release" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
"updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
"created_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS news_content (
|
||||
"id" bigserial primary key,
|
||||
"news_id" int,
|
||||
"en" TEXT NOT NULL,
|
||||
"ru" TEXT NOT NULL,
|
||||
"tm" TEXT NOT NULL,
|
||||
"updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
"created_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
CONSTRAINT news_content_news_id_key UNIQUE ("news_id"),
|
||||
CONSTRAINT news_id_fk
|
||||
FOREIGN KEY ("news_id")
|
||||
REFERENCES news("id")
|
||||
ON UPDATE CASCADE ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS static (
|
||||
"id" bigserial primary key,
|
||||
"logo" character varying(250) NOT NULL DEFAULT '',
|
||||
"title" json NOT NULL DEFAULT '{}'::json,
|
||||
"content_tm" TEXT NOT NULL DEFAULT '',
|
||||
"content_ru" TEXT NOT NULL DEFAULT '',
|
||||
"content_en" TEXT NOT NULL DEFAULT '',
|
||||
"updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
"created_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS currency (
|
||||
"id" bigserial primary key,
|
||||
"title" json NOT NULL DEFAULT '{}'::json,
|
||||
"content_tm" TEXT NOT NULL DEFAULT '',
|
||||
"content_ru" TEXT NOT NULL DEFAULT '',
|
||||
"content_en" TEXT NOT NULL DEFAULT '',
|
||||
"path" character varying(250) NOT NULL DEFAULT '',
|
||||
"updated_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
|
||||
"created_at" TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL
|
||||
);
|
||||
13
backend/deployment/Dockerfile.minio
Executable file
13
backend/deployment/Dockerfile.minio
Executable file
@@ -0,0 +1,13 @@
|
||||
FROM quay.io/minio/minio
|
||||
|
||||
RUN mkdir /storage
|
||||
|
||||
VOLUME /storage
|
||||
|
||||
ENV MINIO_ROOT_USER=MINIO_ROOT_USER
|
||||
ENV MINIO_ROOT_PASSWORD=MINIO_ROOT_PASSWORD
|
||||
ENV MINIO_VOLUMES="/storage"
|
||||
EXPOSE 9000
|
||||
EXPOSE 9093
|
||||
|
||||
CMD ["minio", "server", "/storage", "--console-address", ":9093"]
|
||||
11
backend/deployment/docker-compose.prod.yaml
Normal file
11
backend/deployment/docker-compose.prod.yaml
Normal file
@@ -0,0 +1,11 @@
|
||||
# Production override: points main-server at the pre-built image from the
|
||||
# self-hosted registry and adds the Watchtower label so it gets auto-updated.
|
||||
#
|
||||
# Deploy on the VPS with:
|
||||
# docker compose -f docker-compose.yaml -f deployment/docker-compose.prod.yaml pull main-server
|
||||
# docker compose -f docker-compose.yaml -f deployment/docker-compose.prod.yaml up -d
|
||||
services:
|
||||
main-server:
|
||||
image: localhost:5000/bankline:latest
|
||||
labels:
|
||||
- "com.centurylinklabs.watchtower.enable=true"
|
||||
3
backend/deployment/registry/.env.example
Normal file
3
backend/deployment/registry/.env.example
Normal file
@@ -0,0 +1,3 @@
|
||||
# Copy to .env and fill in.
|
||||
# Generate a token with: openssl rand -hex 32
|
||||
WATCHTOWER_TOKEN=
|
||||
18
backend/deployment/registry/create-user.sh
Executable file
18
backend/deployment/registry/create-user.sh
Executable file
@@ -0,0 +1,18 @@
|
||||
#!/bin/sh
|
||||
# Usage: ./create-user.sh <username> <password>
|
||||
# Appends (or creates) the htpasswd file the registry uses for auth.
|
||||
set -e
|
||||
|
||||
if [ $# -ne 2 ]; then
|
||||
echo "Usage: $0 <username> <password>" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
AUTH_DIR="$SCRIPT_DIR/auth"
|
||||
mkdir -p "$AUTH_DIR"
|
||||
|
||||
docker run --rm --entrypoint htpasswd httpd:2.4-alpine -Bbn "$1" "$2" \
|
||||
>> "$AUTH_DIR/htpasswd"
|
||||
|
||||
echo "Added/updated user '$1' in $AUTH_DIR/htpasswd"
|
||||
38
backend/deployment/registry/docker-compose.yaml
Normal file
38
backend/deployment/registry/docker-compose.yaml
Normal file
@@ -0,0 +1,38 @@
|
||||
services:
|
||||
registry:
|
||||
image: registry:2
|
||||
container_name: docker-registry
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- REGISTRY_AUTH=htpasswd
|
||||
- REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm
|
||||
- REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd
|
||||
- REGISTRY_STORAGE_DELETE_ENABLED=true
|
||||
ports:
|
||||
# Only reachable from the VPS itself. Docker treats 127.0.0.0/8 as
|
||||
# trusted, so pushes/pulls work here without TLS. Reach it from
|
||||
# elsewhere via an SSH tunnel (see scripts/deploy.sh).
|
||||
- "127.0.0.1:5000:5000"
|
||||
volumes:
|
||||
- registry-data:/var/lib/registry
|
||||
- ./auth:/auth:ro
|
||||
|
||||
watchtower:
|
||||
image: containrrr/watchtower
|
||||
container_name: watchtower
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- WATCHTOWER_LABEL_ENABLE=true
|
||||
- WATCHTOWER_HTTP_API_UPDATE=true
|
||||
- WATCHTOWER_HTTP_API_TOKEN=${WATCHTOWER_TOKEN}
|
||||
- WATCHTOWER_CLEANUP=true
|
||||
ports:
|
||||
- "127.0.0.1:8080:8080"
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
# Reuses the VPS's own `docker login localhost:5000` credentials
|
||||
# so Watchtower can pull the private image.
|
||||
- ~/.docker/config.json:/config.json:ro
|
||||
|
||||
volumes:
|
||||
registry-data:
|
||||
56
backend/docker-compose.yaml
Executable file
56
backend/docker-compose.yaml
Executable file
@@ -0,0 +1,56 @@
|
||||
services:
|
||||
main-db:
|
||||
image: postgres:18-alpine
|
||||
container_name: "main-db"
|
||||
restart: always
|
||||
environment:
|
||||
- POSTGRES_USER=bank_admin
|
||||
- POSTGRES_PASSWORD=bank@#23#@_password
|
||||
- POSTGRES_DB=bank_db
|
||||
ports:
|
||||
- '5424:5432'
|
||||
volumes:
|
||||
- main-db-storage-pg18:/var/lib/postgresql
|
||||
networks:
|
||||
- myNetwork
|
||||
main-server:
|
||||
image: main-app
|
||||
restart: unless-stopped
|
||||
container_name: "main-app"
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
ports:
|
||||
- "5050:5050"
|
||||
volumes:
|
||||
- ./public:/app/public
|
||||
depends_on:
|
||||
- main-db
|
||||
networks:
|
||||
- myNetwork
|
||||
|
||||
main-minio:
|
||||
container_name: main-minio
|
||||
build:
|
||||
context: .
|
||||
dockerfile: deployment/Dockerfile.minio
|
||||
ports:
|
||||
- '9003:9000'
|
||||
- '9093:9093'
|
||||
depends_on:
|
||||
- main-db
|
||||
volumes:
|
||||
- main-minio-storage:/storage
|
||||
networks:
|
||||
- myNetwork
|
||||
|
||||
volumes:
|
||||
main-db-storage-pg18:
|
||||
external: true
|
||||
name: bankline_main-db-storage-pg18
|
||||
main-minio-storage:
|
||||
|
||||
networks:
|
||||
myNetwork:
|
||||
driver: bridge
|
||||
|
||||
2800
backend/docs/docs.go
Normal file
2800
backend/docs/docs.go
Normal file
File diff suppressed because it is too large
Load Diff
2776
backend/docs/swagger.json
Normal file
2776
backend/docs/swagger.json
Normal file
File diff suppressed because it is too large
Load Diff
1759
backend/docs/swagger.yaml
Normal file
1759
backend/docs/swagger.yaml
Normal file
File diff suppressed because it is too large
Load Diff
91
backend/go.mod
Normal file
91
backend/go.mod
Normal file
@@ -0,0 +1,91 @@
|
||||
module bankline
|
||||
|
||||
go 1.26.4
|
||||
|
||||
require (
|
||||
github.com/gin-contrib/cors v1.7.7
|
||||
github.com/gin-gonic/gin v1.12.0
|
||||
github.com/go-playground/validator/v10 v10.30.3
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible
|
||||
github.com/ilyakaznacheev/cleanenv v1.5.0
|
||||
github.com/jackc/pgconn v1.14.3
|
||||
github.com/jackc/pgx/v4 v4.18.3
|
||||
github.com/lib/pq v1.12.3
|
||||
github.com/minio/minio-go/v7 v7.2.1
|
||||
github.com/pashagolub/pgxmock v1.8.0
|
||||
github.com/sirupsen/logrus v1.9.4
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/swaggo/files v1.0.1
|
||||
github.com/swaggo/gin-swagger v1.6.1
|
||||
github.com/swaggo/swag v1.16.6
|
||||
golang.org/x/crypto v0.53.0
|
||||
golang.org/x/net v0.56.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.6.0 // indirect
|
||||
github.com/KyleBanks/depth v1.2.1 // indirect
|
||||
github.com/PuerkitoBio/purell v1.1.1 // indirect
|
||||
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
|
||||
github.com/bytedance/gopkg v0.1.3 // indirect
|
||||
github.com/bytedance/sonic v1.15.0 // indirect
|
||||
github.com/bytedance/sonic/loader v0.5.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.19.5 // indirect
|
||||
github.com/go-openapi/jsonreference v0.19.6 // indirect
|
||||
github.com/go-openapi/spec v0.20.4 // indirect
|
||||
github.com/go-openapi/swag v0.19.15 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/goccy/go-yaml v1.19.2 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
|
||||
github.com/jackc/pgio v1.0.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgproto3/v2 v2.3.3 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||
github.com/jackc/pgtype v1.14.0 // indirect
|
||||
github.com/jackc/puddle v1.3.0 // indirect
|
||||
github.com/joho/godotenv v1.5.1 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/compress v1.18.6 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/klauspost/crc32 v1.3.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mailru/easyjson v0.7.6 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/minio/crc64nvme v1.1.1 // indirect
|
||||
github.com/minio/md5-simd v1.1.2 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.3.1 // indirect
|
||||
github.com/philhofer/fwd v1.2.0 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/quic-go/quic-go v0.59.0 // indirect
|
||||
github.com/rs/xid v1.6.0 // indirect
|
||||
github.com/tinylib/msgp v1.6.1 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.1 // indirect
|
||||
github.com/zeebo/xxh3 v1.1.0 // indirect
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/arch v0.23.0 // indirect
|
||||
golang.org/x/mod v0.36.0 // indirect
|
||||
golang.org/x/sync v0.21.0 // indirect
|
||||
golang.org/x/sys v0.46.0 // indirect
|
||||
golang.org/x/text v0.38.0 // indirect
|
||||
golang.org/x/tools v0.45.0 // indirect
|
||||
google.golang.org/protobuf v1.36.10 // indirect
|
||||
gopkg.in/ini.v1 v1.67.2 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3 // indirect
|
||||
)
|
||||
370
backend/go.sum
Normal file
370
backend/go.sum
Normal file
@@ -0,0 +1,370 @@
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
|
||||
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
|
||||
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
|
||||
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
|
||||
github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs=
|
||||
github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI=
|
||||
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
|
||||
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=
|
||||
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
|
||||
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
|
||||
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
|
||||
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
|
||||
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
|
||||
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
|
||||
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/cockroachdb/apd v1.1.0 h1:3LFP3629v+1aKXU5Q37mxmRxX/pIu1nijXydLShEq5I=
|
||||
github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ=
|
||||
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
|
||||
github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
|
||||
github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
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/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
|
||||
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/gin-contrib/cors v1.7.7 h1:Oh9joP463x7Mw72vhvJ61YQm8ODh9b04YR7vsOErD0Q=
|
||||
github.com/gin-contrib/cors v1.7.7/go.mod h1:K5tW0RkzJtWSiOdikXloy8VEZlgdVNpHNw8FpjUPNrE=
|
||||
github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4=
|
||||
github.com/gin-contrib/gzip v0.0.6/go.mod h1:QOJlmV2xmayAjkNS2Y8NQsMneuRShOU/kjovCXNuzzk=
|
||||
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
||||
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
|
||||
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
|
||||
github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY=
|
||||
github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A=
|
||||
github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
|
||||
github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=
|
||||
github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
|
||||
github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs=
|
||||
github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns=
|
||||
github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M=
|
||||
github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I=
|
||||
github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=
|
||||
github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM=
|
||||
github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.30.3 h1:4MU6YkEwx7GbcPJOZxrtbu+QfF3pJLJuaYTeAH0DYy8=
|
||||
github.com/go-playground/validator/v10 v10.30.3/go.mod h1:4Axh7oCNGcoGkqLoE4YWt6n20mcEIsPRlB7vPk3lpyc=
|
||||
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
|
||||
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||
github.com/gofrs/uuid v4.0.0+incompatible h1:1SD/1F5pU8p29ybwgQSwpQk+mwdRrXCYuPhW6m+TnJw=
|
||||
github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
|
||||
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.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/ilyakaznacheev/cleanenv v1.5.0 h1:0VNZXggJE2OYdXE87bfSSwGxeiGt9moSR2lOrsHHvr4=
|
||||
github.com/ilyakaznacheev/cleanenv v1.5.0/go.mod h1:a5aDzaJrLCQZsazHol1w8InnDcOX0OColm64SlIi6gk=
|
||||
github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo=
|
||||
github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk=
|
||||
github.com/jackc/chunkreader/v2 v2.0.1 h1:i+RDz65UE+mmpjTfyz0MoVTnzeYxroil2G82ki7MGG8=
|
||||
github.com/jackc/chunkreader/v2 v2.0.1/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk=
|
||||
github.com/jackc/pgconn v0.0.0-20190420214824-7e0022ef6ba3/go.mod h1:jkELnwuX+w9qN5YIfX0fl88Ehu4XC3keFuOJJk9pcnA=
|
||||
github.com/jackc/pgconn v0.0.0-20190824142844-760dd75542eb/go.mod h1:lLjNuW/+OfW9/pnVKPazfWOgNfH2aPem8YQ7ilXGvJE=
|
||||
github.com/jackc/pgconn v0.0.0-20190831204454-2fabfa3c18b7/go.mod h1:ZJKsE/KZfsUgOEh9hBm+xYTstcNHg7UPMVJqRfQxq4s=
|
||||
github.com/jackc/pgconn v1.8.0/go.mod h1:1C2Pb36bGIP9QHGBYCjnyhqu7Rv3sGshaQUvmfGIB/o=
|
||||
github.com/jackc/pgconn v1.9.0/go.mod h1:YctiPyvzfU11JFxoXokUOOKQXQmDMoJL9vJzHH8/2JY=
|
||||
github.com/jackc/pgconn v1.9.1-0.20210724152538-d89c8390a530/go.mod h1:4z2w8XhRbP1hYxkpTuBjTS3ne3J48K83+u0zoyvg2pI=
|
||||
github.com/jackc/pgconn v1.14.3 h1:bVoTr12EGANZz66nZPkMInAV/KHD2TxH9npjXXgiB3w=
|
||||
github.com/jackc/pgconn v1.14.3/go.mod h1:RZbme4uasqzybK2RK5c65VsHxoyaml09lx3tXOcO/VM=
|
||||
github.com/jackc/pgio v1.0.0 h1:g12B9UwVnzGhueNavwioyEEpAmqMe1E/BN9ES+8ovkE=
|
||||
github.com/jackc/pgio v1.0.0/go.mod h1:oP+2QK2wFfUWgr+gxjoBH9KGBb31Eio69xUb0w5bYf8=
|
||||
github.com/jackc/pgmock v0.0.0-20190831213851-13a1b77aafa2/go.mod h1:fGZlG77KXmcq05nJLRkk0+p82V8B8Dw8KN2/V9c/OAE=
|
||||
github.com/jackc/pgmock v0.0.0-20201204152224-4fe30f7445fd/go.mod h1:hrBW0Enj2AZTNpt/7Y5rr2xe/9Mn757Wtb2xeBzPv2c=
|
||||
github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65 h1:DadwsjnMwFjfWc9y5Wi/+Zz7xoE5ALHsRQlOctkOiHc=
|
||||
github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65/go.mod h1:5R2h2EEX+qri8jOWMbJCtaPWkrrNc7OHwsp2TCqp7ak=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgproto3 v1.1.0/go.mod h1:eR5FA3leWg7p9aeAqi37XOTgTIbkABlvcPB3E5rlc78=
|
||||
github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190420180111-c116219b62db/go.mod h1:bhq50y+xrl9n5mRYyCBFKkpRVTLYJVWeCc+mEAI3yXA=
|
||||
github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190609003834-432c2951c711/go.mod h1:uH0AWtUmuShn0bcesswc4aBTWGvw0cAxIJp+6OB//Wg=
|
||||
github.com/jackc/pgproto3/v2 v2.0.0-rc3/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM=
|
||||
github.com/jackc/pgproto3/v2 v2.0.0-rc3.0.20190831210041-4c03ce451f29/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM=
|
||||
github.com/jackc/pgproto3/v2 v2.0.6/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA=
|
||||
github.com/jackc/pgproto3/v2 v2.1.1/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA=
|
||||
github.com/jackc/pgproto3/v2 v2.3.3 h1:1HLSx5H+tXR9pW3in3zaztoEwQYRC9SQaYUHjTSUOag=
|
||||
github.com/jackc/pgproto3/v2 v2.3.3/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA=
|
||||
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b/go.mod h1:vsD4gTJCa9TptPL8sPkXrLZ+hDuNrZCnj29CQpr4X1E=
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgtype v0.0.0-20190421001408-4ed0de4755e0/go.mod h1:hdSHsc1V01CGwFsrv11mJRHWJ6aifDLfdV3aVjFF0zg=
|
||||
github.com/jackc/pgtype v0.0.0-20190824184912-ab885b375b90/go.mod h1:KcahbBH1nCMSo2DXpzsoWOAfFkdEtEJpPbVLq8eE+mc=
|
||||
github.com/jackc/pgtype v0.0.0-20190828014616-a8802b16cc59/go.mod h1:MWlu30kVJrUS8lot6TQqcg7mtthZ9T0EoIBFiJcmcyw=
|
||||
github.com/jackc/pgtype v1.8.1-0.20210724151600-32e20a603178/go.mod h1:C516IlIV9NKqfsMCXTdChteoXmwgUceqaLfjg2e3NlM=
|
||||
github.com/jackc/pgtype v1.14.0 h1:y+xUdabmyMkJLyApYuPj38mW+aAIqCe5uuBB51rH3Vw=
|
||||
github.com/jackc/pgtype v1.14.0/go.mod h1:LUMuVrfsFfdKGLw+AFFVv6KtHOFMwRgDDzBt76IqCA4=
|
||||
github.com/jackc/pgx/v4 v4.0.0-20190420224344-cc3461e65d96/go.mod h1:mdxmSJJuR08CZQyj1PVQBHy9XOp5p8/SHH6a0psbY9Y=
|
||||
github.com/jackc/pgx/v4 v4.0.0-20190421002000-1b8f0016e912/go.mod h1:no/Y67Jkk/9WuGR0JG/JseM9irFbnEPbuWV2EELPNuM=
|
||||
github.com/jackc/pgx/v4 v4.0.0-pre1.0.20190824185557-6972a5742186/go.mod h1:X+GQnOEnf1dqHGpw7JmHqHc1NxDoalibchSk9/RWuDc=
|
||||
github.com/jackc/pgx/v4 v4.12.1-0.20210724153913-640aa07df17c/go.mod h1:1QD0+tgSXP7iUjYm9C1NxKhny7lq6ee99u/z+IHFcgs=
|
||||
github.com/jackc/pgx/v4 v4.18.3 h1:dE2/TrEsGX3RBprb3qryqSV9Y60iZN1C6i8IrmW9/BA=
|
||||
github.com/jackc/pgx/v4 v4.18.3/go.mod h1:Ey4Oru5tH5sB6tV7hDmfWFahwF15Eb7DNXlRKx2CkVw=
|
||||
github.com/jackc/puddle v0.0.0-20190413234325-e4ced69a3a2b/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
|
||||
github.com/jackc/puddle v0.0.0-20190608224051-11cab39313c9/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
|
||||
github.com/jackc/puddle v1.1.3/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
|
||||
github.com/jackc/puddle v1.3.0 h1:eHK/5clGOatcjX3oWGBO/MpxpbHzSwud5EWTSCI+MX0=
|
||||
github.com/jackc/puddle v1.3.0/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
|
||||
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
|
||||
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM=
|
||||
github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
|
||||
github.com/lib/pq v1.1.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
|
||||
github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
|
||||
github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/lib/pq v1.12.3 h1:tTWxr2YLKwIvK90ZXEw8GP7UFHtcbTtty8zsI+YjrfQ=
|
||||
github.com/lib/pq v1.12.3/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
|
||||
github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
|
||||
github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
|
||||
github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA=
|
||||
github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
|
||||
github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ=
|
||||
github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
|
||||
github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
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/minio/crc64nvme v1.1.1 h1:8dwx/Pz49suywbO+auHCBpCtlW1OfpcLN7wYgVR6wAI=
|
||||
github.com/minio/crc64nvme v1.1.1/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg=
|
||||
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
|
||||
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
|
||||
github.com/minio/minio-go/v7 v7.2.1 h1:PfBfwvKB/MmqyN8Vb1G9voWisaM9OrLv+WwOvMwS9Dw=
|
||||
github.com/minio/minio-go/v7 v7.2.1/go.mod h1:EU9hENAStx/xXduNdrGO5e4X5vk19NtgB+RIPjZO8o0=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/pashagolub/pgxmock v1.8.0 h1:05JB+jng7yPdeC6i04i8TC4H1Kr7TfcFeQyf4JP6534=
|
||||
github.com/pashagolub/pgxmock v1.8.0/go.mod h1:kDkER7/KJdD3HQjNvFw5siwR7yREKmMvwf8VhAgTK5o=
|
||||
github.com/pelletier/go-toml/v2 v2.3.1 h1:MYEvvGnQjeNkRF1qUuGolNtNExTDwct51yp7olPtrEc=
|
||||
github.com/pelletier/go-toml/v2 v2.3.1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
|
||||
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
|
||||
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
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/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
|
||||
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
|
||||
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ=
|
||||
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||
github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU=
|
||||
github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc=
|
||||
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
|
||||
github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4=
|
||||
github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ=
|
||||
github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
|
||||
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
|
||||
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
|
||||
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
|
||||
github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE=
|
||||
github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg=
|
||||
github.com/swaggo/gin-swagger v1.6.1 h1:Ri06G4gc9N4t4k8hekMigJ9zKTFSlqj/9paAQCQs7cY=
|
||||
github.com/swaggo/gin-swagger v1.6.1/go.mod h1:LQ+hJStHakCWRiK/YNYtJOu4mR2FP+pxLnILT/qNiTw=
|
||||
github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=
|
||||
github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=
|
||||
github.com/tinylib/msgp v1.6.1 h1:ESRv8eL3u+DNHUoSAAQRE50Hm162zqAnBoGv9PzScPY=
|
||||
github.com/tinylib/msgp v1.6.1/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
|
||||
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ=
|
||||
github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
|
||||
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||
github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q=
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
|
||||
go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
|
||||
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
|
||||
go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
|
||||
go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
|
||||
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
|
||||
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
|
||||
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
|
||||
go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4=
|
||||
go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU=
|
||||
go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA=
|
||||
go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
|
||||
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
|
||||
go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/arch v0.23.0 h1:lKF64A2jF6Zd8L0knGltUnegD62JMFBiCPBmQpToHhg=
|
||||
golang.org/x/arch v0.23.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE=
|
||||
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
|
||||
golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
|
||||
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
|
||||
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
|
||||
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4=
|
||||
golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
|
||||
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
|
||||
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
|
||||
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
|
||||
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190425163242-31fd60d6bfdc/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
||||
golang.org/x/tools v0.0.0-20190823170909-c4a336ef6a2f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8=
|
||||
golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0=
|
||||
golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
|
||||
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||
gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:aPpfJ7XW+gOuirDoZ8gHhLh3kZ1B08FtV2bbmy7Jv3s=
|
||||
gopkg.in/ini.v1 v1.67.2 h1:JtOSMb9OuaCZKr7h5D/h6iii14sK0hLbplTc6frx4Ss=
|
||||
gopkg.in/ini.v1 v1.67.2/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/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=
|
||||
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
|
||||
olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3 h1:slmdOY3vp8a7KQbHkL+FLbvbkgMqmXojpFUO/jENuqQ=
|
||||
olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3/go.mod h1:oVgVk4OWVDi43qWBEyGhXgYxt7+ED4iYNpTngSLX2Iw=
|
||||
BIN
backend/internal/.DS_Store
vendored
Normal file
BIN
backend/internal/.DS_Store
vendored
Normal file
Binary file not shown.
BIN
backend/internal/admin/.DS_Store
vendored
Normal file
BIN
backend/internal/admin/.DS_Store
vendored
Normal file
Binary file not shown.
88
backend/internal/admin/auth/db/postgresql.go
Executable file
88
backend/internal/admin/auth/db/postgresql.go
Executable file
@@ -0,0 +1,88 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/auth"
|
||||
"bankline/pkg/client/postgresql"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"strconv"
|
||||
|
||||
_ "github.com/lib/pq"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) auth.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repository) Login(ctx context.Context, dto auth.LoginDTO) (auth.ResLoginDTO, error) {
|
||||
var (
|
||||
result auth.ResLoginDTO
|
||||
)
|
||||
|
||||
q := `select
|
||||
id, password
|
||||
from admin
|
||||
where login = $1 ;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, dto.Login).Scan(&result.Id, &result.Password)
|
||||
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *repository) CheckAdmin(ctx context.Context, id int) (auth.ResLoginDTO, error) {
|
||||
|
||||
var (
|
||||
result auth.ResLoginDTO
|
||||
)
|
||||
|
||||
q := `select
|
||||
id, password
|
||||
from admin
|
||||
where id = $1 ;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, id).Scan(&result.Id, &result.Password)
|
||||
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *repository) GetProfile(ctx context.Context, uuid string) (auth.ResUserDTO, error) {
|
||||
|
||||
var (
|
||||
ad auth.ResUserDTO
|
||||
)
|
||||
id, _ := strconv.Atoi(uuid)
|
||||
|
||||
q := `select
|
||||
id, fullname,
|
||||
phone_number, avatar,
|
||||
created_at
|
||||
from admin
|
||||
where id = $1;`
|
||||
err := r.client.QueryRow(ctx, q, id).Scan(
|
||||
&ad.Id, &ad.FullName,
|
||||
&ad.PhoneNumber, &ad.Avatar,
|
||||
&ad.CreatedAt,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return ad, err
|
||||
}
|
||||
|
||||
return ad, nil
|
||||
}
|
||||
81
backend/internal/admin/auth/db/postgresql_test.go
Normal file
81
backend/internal/admin/auth/db/postgresql_test.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/auth"
|
||||
"bankline/pkg/logging"
|
||||
"errors"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"golang.org/x/net/context"
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
"github.com/pashagolub/pgxmock"
|
||||
)
|
||||
|
||||
var (
|
||||
// prepare mock
|
||||
colums = []string{"id", "password"}
|
||||
|
||||
// request
|
||||
req = auth.LoginDTO{
|
||||
Login: "admin@admin.com",
|
||||
}
|
||||
|
||||
// expected
|
||||
want = auth.ResLoginDTO{
|
||||
Id: 1,
|
||||
Password: "$2a$10$odpKFHq.px.VgROs0ogaJezXZbwmFxImvG9AqOJizV9osbtuNqZ5i",
|
||||
}
|
||||
)
|
||||
|
||||
// Setup will prepare mock and account service instance
|
||||
func Run(t *testing.T) pgxmock.PgxPoolIface {
|
||||
t.Helper()
|
||||
mock, err := pgxmock.NewPool()
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error occur: %v\n", err)
|
||||
}
|
||||
defer mock.Close()
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
func TestGet(t *testing.T) {
|
||||
mock := Run(t)
|
||||
q := `select id, password from admin where login = $1 ;`
|
||||
|
||||
t.Run("EXPECT SUCCESS", func(t *testing.T) {
|
||||
mock.ExpectQuery(regexp.QuoteMeta(q)).
|
||||
WithArgs(req.Login).
|
||||
WillReturnRows(mock.NewRows(colums).
|
||||
AddRow(1, "$2a$10$odpKFHq.px.VgROs0ogaJezXZbwmFxImvG9AqOJizV9osbtuNqZ5i"))
|
||||
|
||||
// actual
|
||||
logger := logging.GetLogger()
|
||||
ops := NewRepository(mock, logger)
|
||||
got, err := ops.Login(context.Background(), req)
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, got.Id, want.Id)
|
||||
assert.Equal(t, got, want)
|
||||
})
|
||||
|
||||
t.Run("EXPECT FAIL", func(t *testing.T) {
|
||||
mock.ExpectQuery(regexp.QuoteMeta(q)).
|
||||
WithArgs(req.Login).
|
||||
WillReturnError(errors.New("error getting user data"))
|
||||
|
||||
// actual
|
||||
logger := logging.GetLogger()
|
||||
ops := NewRepository(mock, logger)
|
||||
got, err := ops.Login(context.Background(), req)
|
||||
assert.Error(t, err)
|
||||
if got.Id == 0 {
|
||||
assert.Nil(t, nil)
|
||||
}
|
||||
})
|
||||
|
||||
if err := mock.ExpectationsWereMet(); err != nil {
|
||||
t.Errorf("there were unfulfilled expectation: %v\n", err)
|
||||
}
|
||||
}
|
||||
29
backend/internal/admin/auth/dto.go
Executable file
29
backend/internal/admin/auth/dto.go
Executable file
@@ -0,0 +1,29 @@
|
||||
package auth
|
||||
|
||||
import "time"
|
||||
|
||||
type LoginDTO struct {
|
||||
Login string `json:"login" binding:"required" required:"this one failed" `
|
||||
Password string `json:"password" binding:"required" required:"this one failed"`
|
||||
}
|
||||
|
||||
type ResLoginDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type TokenReqBody struct {
|
||||
RefreshToken string `json:"refreshToken"`
|
||||
}
|
||||
|
||||
type ReqDTO struct {
|
||||
Id int `json:"Id"`
|
||||
}
|
||||
|
||||
type ResUserDTO struct {
|
||||
Id int `json:"Id"`
|
||||
FullName string `json:"fullName"`
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
Avatar string `json:"avatar"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
320
backend/internal/admin/auth/handler.go
Executable file
320
backend/internal/admin/auth/handler.go
Executable file
@@ -0,0 +1,320 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
_ "bankline/docs"
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/config"
|
||||
"bankline/internal/handlers"
|
||||
"bankline/pkg/logging"
|
||||
"bankline/pkg/utils"
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
minioUpload "bankline/pkg/minio"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt"
|
||||
)
|
||||
|
||||
const (
|
||||
loginURL = "/login"
|
||||
tokenURL = "/token"
|
||||
|
||||
getProfileURL = "/get-profile"
|
||||
fileUploadURL = "/file"
|
||||
fileRemoveURL = "/file/:id"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{
|
||||
logger: logger,
|
||||
repository: repository,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
router.POST(loginURL, h.login)
|
||||
router.GET(getProfileURL, appresult.JwtTokenCheck(), h.getProfile)
|
||||
router.POST(fileUploadURL, appresult.JwtTokenCheck(), h.fileUpload)
|
||||
router.DELETE(fileRemoveURL, appresult.JwtTokenCheck(), h.DeleteObject)
|
||||
router.POST(tokenURL, h.token)
|
||||
|
||||
}
|
||||
|
||||
// =================================================================================
|
||||
|
||||
// login godoc
|
||||
// @Description login for Admin
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param auth body LoginDTO true "Login JSON"
|
||||
// @Success 200 {string} string true "token"
|
||||
// @Router /admin/login [post]
|
||||
func (h *handler) login(c *gin.Context) {
|
||||
|
||||
var (
|
||||
loginReq LoginDTO
|
||||
)
|
||||
if err := c.ShouldBindJSON(&loginReq); err != nil {
|
||||
fmt.Println("err in login", err)
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.repository.Login(context.TODO(), loginReq)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
password := []byte(fmt.Sprint(loginReq.Password))
|
||||
oldHash := []byte(fmt.Sprint(res.Password))
|
||||
errCompareHash := bcrypt.CompareHashAndPassword(oldHash, password)
|
||||
if errCompareHash != nil {
|
||||
fmt.Println("errCompareHash", errCompareHash)
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
newTokenPair, err := utils.GenerateTokenPair(res.Id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = newTokenPair
|
||||
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// getProfile godoc
|
||||
// @Description profile data for Admin
|
||||
// @Tags admin
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} ResUserDTO
|
||||
// @Router /admin/get-profile [get]
|
||||
func (h *handler) getProfile(c *gin.Context) {
|
||||
uuid := c.Keys["id"]
|
||||
fmt.Println("uuid ----", uuid)
|
||||
dt, err := h.repository.GetProfile(context.Background(), fmt.Sprint(uuid))
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = dt
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// fileUpload godoc
|
||||
// @Description file upload
|
||||
// @Tags file-upload
|
||||
//
|
||||
// @Accept multipart/form-data
|
||||
// @Produce json
|
||||
// @Param file formData file true "this is a test file"
|
||||
//
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/file [post]
|
||||
func (h *handler) fileUpload(c *gin.Context) {
|
||||
|
||||
file, header, err := c.Request.FormFile("file")
|
||||
if err != nil {
|
||||
c.String(http.StatusBadRequest, "get form err: %s", err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
defer func(file multipart.File) {
|
||||
err := file.Close()
|
||||
if err != nil {
|
||||
fmt.Println("hello", err)
|
||||
}
|
||||
}(file)
|
||||
|
||||
cfg := config.GetConfig()
|
||||
appDirPath := cfg.PublicFilePath + "/images/"
|
||||
|
||||
err = os.MkdirAll(appDirPath, os.ModePerm)
|
||||
if err != nil {
|
||||
fmt.Println("wwwww", err)
|
||||
}
|
||||
|
||||
appName := fmt.Sprintf("%d%s", time.Now().UnixNano(), filepath.Ext(header.Filename))
|
||||
dbPath := "/images/" + appName
|
||||
|
||||
minioClient, err := minioUpload.ConnectionMinio()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "connection to MinIO failed"})
|
||||
return
|
||||
}
|
||||
|
||||
contentType := header.Header.Get("Content-Type")
|
||||
ctx := context.Background()
|
||||
|
||||
if err := minioUpload.EnsureBucket(ctx, minioClient); err != nil {
|
||||
fmt.Println("ensure bucket:", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create MinIO bucket"})
|
||||
return
|
||||
}
|
||||
|
||||
size := header.Size
|
||||
if size <= 0 {
|
||||
size = -1
|
||||
}
|
||||
_, err = minioClient.PutObject(ctx, minioUpload.BucketName, appName, file, size, minio.PutObjectOptions{ContentType: contentType})
|
||||
if err != nil {
|
||||
fmt.Println("Error uploading file to MinIO:", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "File upload to MinIO failed"})
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = dbPath
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func GetObject(c *gin.Context) {
|
||||
|
||||
id := c.Param("id")
|
||||
minioClient, err := minioUpload.ConnectionMinio()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "connection to MinIO failed"})
|
||||
return
|
||||
}
|
||||
|
||||
object, err := minioClient.GetObject(context.Background(), minioUpload.BucketName, id, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
fmt.Println("Error connection:", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
contentBytes := StreamToByte(object)
|
||||
contentType := http.DetectContentType(contentBytes)
|
||||
c.Data(http.StatusOK, contentType, contentBytes)
|
||||
}
|
||||
|
||||
func StreamToByte(stream io.Reader) []byte {
|
||||
buf := new(bytes.Buffer)
|
||||
_, _ = buf.ReadFrom(stream)
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// DeleteObject godoc
|
||||
// @Description remove file
|
||||
// @Tags file-upload
|
||||
//
|
||||
// @Accept multipart/form-data
|
||||
// @Produce json
|
||||
//
|
||||
// @Param id path string true "file path"
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/file/{id} [delete]
|
||||
func (h *handler) DeleteObject(c *gin.Context) {
|
||||
|
||||
id := c.Param("id")
|
||||
minioClient, err := minioUpload.ConnectionMinio()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "connection to MinIO failed"})
|
||||
return
|
||||
}
|
||||
|
||||
suc, err := DeleteItemInMinio(context.Background(), minioClient, id)
|
||||
if err != nil {
|
||||
fmt.Println("Error connection:", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
successResult := appresult.Success
|
||||
successResult.Data = suc
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
func DeleteItemInMinio(ctx context.Context, minioClient *minio.Client, value string) (string, error) {
|
||||
err := minioClient.RemoveObject(ctx, minioUpload.BucketName, value, minio.RemoveObjectOptions{GovernanceBypass: true})
|
||||
if err != nil {
|
||||
fmt.Println("error remove file in minio:", err)
|
||||
return "", err
|
||||
}
|
||||
return "File successfully removed!!!", nil
|
||||
}
|
||||
|
||||
// token godoc
|
||||
// @Description token for Admin
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param auth body TokenReqBody true "Token JSON"
|
||||
// @Success 200 {string} string true "token"
|
||||
// @Router /admin/token [post]
|
||||
func (h *handler) token(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
tokenReq TokenReqBody
|
||||
)
|
||||
|
||||
if err = c.ShouldBindJSON(&tokenReq); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
token, err := jwt.Parse(tokenReq.RefreshToken, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(utils.SecretKey), nil
|
||||
})
|
||||
|
||||
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
||||
|
||||
res, err := h.repository.CheckAdmin(context.TODO(), int(claims["id"].(float64)))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
if int(claims["id"].(float64)) == res.Id {
|
||||
|
||||
newTokenPair, err := utils.GenerateTokenPair(int(claims["id"].(float64)))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = newTokenPair
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
9
backend/internal/admin/auth/storage.go
Executable file
9
backend/internal/admin/auth/storage.go
Executable file
@@ -0,0 +1,9 @@
|
||||
package auth
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
Login(ctx context.Context, dto LoginDTO) (ResLoginDTO, error)
|
||||
CheckAdmin(ctx context.Context, id int) (ResLoginDTO, error)
|
||||
GetProfile(ctx context.Context, req string) (ResUserDTO, error)
|
||||
}
|
||||
167
backend/internal/admin/banner/db/postgresql.go
Executable file
167
backend/internal/admin/banner/db/postgresql.go
Executable file
@@ -0,0 +1,167 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/banner"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client *pgxpool.Pool
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client *pgxpool.Pool, logger *logging.Logger) banner.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
var sortColumns = map[string]string{
|
||||
"id": "id",
|
||||
"createdAt": "created_at",
|
||||
}
|
||||
|
||||
func (r repository) GetAllData(ctx context.Context, params listing.Params) (banner.DataBannerDTO, error) {
|
||||
|
||||
ns := []banner.GetBannerDTO{}
|
||||
var (
|
||||
dt banner.DataBannerDTO
|
||||
err error
|
||||
rows pgx.Rows
|
||||
)
|
||||
|
||||
where := ""
|
||||
args := []interface{}{}
|
||||
if params.Search != "" {
|
||||
where = ` where title::text ILIKE $1 or content_tm ILIKE $1 or content_ru ILIKE $1 or content_en ILIKE $1 `
|
||||
args = append(args, params.SearchPattern())
|
||||
}
|
||||
|
||||
qC := `select count(*) from banner` + where + `;`
|
||||
r.client.QueryRow(ctx, qC, args...).Scan(&dt.Count)
|
||||
|
||||
q := ` select
|
||||
id, title,
|
||||
content_tm, content_ru, content_en,
|
||||
img, created_at
|
||||
from banner` +
|
||||
where +
|
||||
params.OrderClause(sortColumns, "created_at DESC")
|
||||
|
||||
if params.Paginated() {
|
||||
q += fmt.Sprintf("limit $%d offset $%d;", len(args)+1, len(args)+2)
|
||||
args = append(args, params.Limit, params.Offset())
|
||||
} else {
|
||||
q += ";"
|
||||
}
|
||||
rows, err = r.client.Query(ctx, q, args...)
|
||||
if err != nil {
|
||||
return dt, nil
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var n banner.GetBannerDTO
|
||||
errN := rows.Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.ContentTm, &n.ContentRu, &n.ContentEn,
|
||||
&n.Image, &n.CreatedAt,
|
||||
)
|
||||
if errN != nil {
|
||||
r.logger.Error("errN :::", errN)
|
||||
continue
|
||||
}
|
||||
|
||||
ns = append(ns, n)
|
||||
}
|
||||
dt.Categories = ns
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) GetOneData(ctx context.Context, id int) (banner.GetBannerDTO, error) {
|
||||
|
||||
var (
|
||||
n banner.GetBannerDTO
|
||||
)
|
||||
|
||||
q := ` select
|
||||
id, title,
|
||||
content_tm, content_ru, content_en,
|
||||
img, created_at
|
||||
from banner where id = $1 ; `
|
||||
|
||||
err := r.client.QueryRow(ctx, q, id).Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.ContentTm, &n.ContentRu, &n.ContentEn,
|
||||
&n.Image, &n.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) AddData(ctx context.Context, req banner.AddBannerDTO) (banner.GetBannerDTO, error) {
|
||||
var (
|
||||
n banner.GetBannerDTO
|
||||
)
|
||||
|
||||
q := `INSERT INTO banner (title, content_tm, content_ru, content_en, img) VALUES ($1, $2, $3, $4, $5) RETURNING id, title,
|
||||
content_tm, content_ru, content_en,
|
||||
img, created_at;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, req.Title, req.ContentTm, req.ContentRu, req.ContentEn, req.Image).Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.ContentTm, &n.ContentRu, &n.ContentEn,
|
||||
&n.Image, &n.CreatedAt,
|
||||
)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return n, err
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) UpdateData(ctx context.Context, req banner.UpdateBannerDTO, id int) (banner.GetBannerDTO, error) {
|
||||
var (
|
||||
q string
|
||||
n banner.GetBannerDTO
|
||||
)
|
||||
|
||||
q = ` update banner set title = $1, content_tm = $2, content_ru = $3, content_en = $4, img = $5 where id = $6 RETURNING id, title,
|
||||
content_tm, content_ru, content_en,
|
||||
img, created_at;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, req.Title, req.ContentTm, req.ContentRu, req.ContentEn, req.Image, id).Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.ContentTm, &n.ContentRu, &n.ContentEn,
|
||||
&n.Image, &n.CreatedAt,
|
||||
)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return n, err
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) DeleteData(ctx context.Context, uuid int) error {
|
||||
var (
|
||||
q string
|
||||
)
|
||||
|
||||
q = ` delete from banner where id = $1 ;`
|
||||
_, err := r.client.Exec(ctx, q, uuid)
|
||||
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
48
backend/internal/admin/banner/dto.go
Executable file
48
backend/internal/admin/banner/dto.go
Executable file
@@ -0,0 +1,48 @@
|
||||
package banner
|
||||
|
||||
import "time"
|
||||
|
||||
type DataBannerDTO struct {
|
||||
Categories []GetBannerDTO `json:"banners"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type Language struct {
|
||||
Tm string `json:"tm"`
|
||||
Ru string `json:"ru"`
|
||||
En string `json:"en"`
|
||||
}
|
||||
|
||||
type GetBannerDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Title Language `json:"title"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
Image string `json:"imagePath"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type AddBannerDTO struct {
|
||||
Title Language `json:"title" binding:"required"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
Image string `json:"imagePath"`
|
||||
}
|
||||
|
||||
type UpdateBannerDTO struct {
|
||||
Title Language `json:"title" binding:"required"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
Image string `json:"imagePath"`
|
||||
}
|
||||
|
||||
type ReqUUIDDTO struct {
|
||||
Id int `json:"Id"`
|
||||
}
|
||||
|
||||
type ReqIDDTO struct {
|
||||
Id int `json:"id"`
|
||||
}
|
||||
212
backend/internal/admin/banner/handler.go
Executable file
212
backend/internal/admin/banner/handler.go
Executable file
@@ -0,0 +1,212 @@
|
||||
package banner
|
||||
|
||||
import (
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/handlers"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
getAllURL = ""
|
||||
getOneURL = "/:id"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
repository Repository
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewHandler(repository Repository, logger *logging.Logger) handlers.Handler {
|
||||
return &handler{
|
||||
repository: repository,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
router.GET(getAllURL, h.GetAll)
|
||||
router.GET(getOneURL, h.GetOne)
|
||||
|
||||
router.POST(getAllURL, h.Create)
|
||||
router.PUT(getOneURL, h.Update)
|
||||
router.DELETE(getOneURL, h.Delete)
|
||||
|
||||
}
|
||||
|
||||
// GetAll godoc
|
||||
// @Description all data banner
|
||||
// @Tags banner
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param limit query int false "limit"
|
||||
// @Param page query int false "page"
|
||||
// @Param search query string false "search term"
|
||||
// @Param sort query string false "sort column (id, createdAt)"
|
||||
// @Param order query string false "sort order (asc, desc)"
|
||||
// @Success 200 {object} DataBannerDTO
|
||||
// @Router /admin/banner [get]
|
||||
func (h *handler) GetAll(c *gin.Context) {
|
||||
result, err := h.repository.GetAllData(context.Background(), listing.FromQuery(c))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetOne godoc
|
||||
// @Description one data banner
|
||||
// @Tags banner
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "banner ID"
|
||||
// @Success 200 {object} GetBannerDTO
|
||||
// @Router /admin/banner/{id} [get]
|
||||
func (h *handler) GetOne(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
fmt.Println("--------------", id)
|
||||
i, err := strconv.Atoi(id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
result, err := h.repository.GetOneData(context.Background(), i)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Create godoc
|
||||
// @Description create banner
|
||||
// @Tags banner
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param banner body AddBannerDTO true "Create JSON"
|
||||
// @Success 200 {object} GetBannerDTO
|
||||
// @Router /admin/banner [post]
|
||||
func (h *handler) Create(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
)
|
||||
|
||||
body, errBody := io.ReadAll(c.Request.Body)
|
||||
if errBody != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
reqDTO := AddBannerDTO{}
|
||||
err = json.Unmarshal(body, &reqDTO)
|
||||
res, err := h.repository.AddData(context.Background(), reqDTO)
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Update godoc
|
||||
// @Description update banner
|
||||
// @Tags banner
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "banner ID"
|
||||
// @Param banner body UpdateBannerDTO true "Create JSON"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/banner/{id} [put]
|
||||
func (h *handler) Update(c *gin.Context) {
|
||||
var (
|
||||
res GetBannerDTO
|
||||
)
|
||||
bannerId := c.Param("id")
|
||||
fmt.Println("--------------", bannerId)
|
||||
id, err := strconv.Atoi(bannerId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
body, errBody := io.ReadAll(c.Request.Body)
|
||||
if errBody != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
reqDTO := UpdateBannerDTO{}
|
||||
err = json.Unmarshal(body, &reqDTO)
|
||||
|
||||
fmt.Println("id :::", id)
|
||||
if id != 0 {
|
||||
res, err = h.repository.UpdateData(context.Background(), reqDTO, id)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Delete godoc
|
||||
// @Description delete banner
|
||||
// @Tags banner
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "banner ID"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/banner/{id} [delete]
|
||||
func (h *handler) Delete(c *gin.Context) {
|
||||
|
||||
bannerId := c.Param("id")
|
||||
fmt.Println("--------------", bannerId)
|
||||
id, err := strconv.Atoi(bannerId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.repository.DeleteData(context.Background(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = ""
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
1
backend/internal/admin/banner/model.go
Executable file
1
backend/internal/admin/banner/model.go
Executable file
@@ -0,0 +1 @@
|
||||
package banner
|
||||
14
backend/internal/admin/banner/storage.go
Executable file
14
backend/internal/admin/banner/storage.go
Executable file
@@ -0,0 +1,14 @@
|
||||
package banner
|
||||
|
||||
import (
|
||||
"bankline/internal/listing"
|
||||
"context"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
GetAllData(ctx context.Context, params listing.Params) (DataBannerDTO, error)
|
||||
GetOneData(ctx context.Context, id int) (GetBannerDTO, error)
|
||||
AddData(ctx context.Context, dto AddBannerDTO) (GetBannerDTO, error)
|
||||
UpdateData(ctx context.Context, dto UpdateBannerDTO, id int) (GetBannerDTO, error)
|
||||
DeleteData(ctx context.Context, id int) error
|
||||
}
|
||||
169
backend/internal/admin/category/db/postgresql.go
Executable file
169
backend/internal/admin/category/db/postgresql.go
Executable file
@@ -0,0 +1,169 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/category"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client *pgxpool.Pool
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client *pgxpool.Pool, logger *logging.Logger) category.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
var sortColumns = map[string]string{
|
||||
"id": "cs.id",
|
||||
"status": "cs.status",
|
||||
"createdAt": "cs.created_at",
|
||||
}
|
||||
|
||||
func (r repository) GetAllData(ctx context.Context, params listing.Params) (category.DataCategoryDTO, error) {
|
||||
|
||||
ns := []category.CategoryDTO{}
|
||||
var (
|
||||
dt category.DataCategoryDTO
|
||||
err error
|
||||
rows pgx.Rows
|
||||
)
|
||||
|
||||
where := ""
|
||||
args := []interface{}{}
|
||||
if params.Search != "" {
|
||||
where = ` where cs.name::text ILIKE $1 `
|
||||
args = append(args, params.SearchPattern())
|
||||
}
|
||||
|
||||
qC := `select count(*) from categories cs` + where + `;`
|
||||
r.client.QueryRow(ctx, qC, args...).Scan(&dt.Count)
|
||||
|
||||
q := ` select
|
||||
cs.Id, cs.name,
|
||||
jsonb_agg(ss.name) as sub_category,
|
||||
cs.status, cs.created_at
|
||||
from categories cs
|
||||
left join sub_categories ss on ss.category_id = cs.Id ` +
|
||||
where +
|
||||
` group by cs.Id ` +
|
||||
params.OrderClause(sortColumns, "cs.created_at ASC")
|
||||
|
||||
if params.Paginated() {
|
||||
q += fmt.Sprintf("limit $%d offset $%d;", len(args)+1, len(args)+2)
|
||||
args = append(args, params.Limit, params.Offset())
|
||||
} else {
|
||||
q += ";"
|
||||
}
|
||||
rows, err = r.client.Query(ctx, q, args...)
|
||||
if err != nil {
|
||||
return dt, nil
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var n category.CategoryDTO
|
||||
errN := rows.Scan(
|
||||
&n.Id, &n.Name, &n.SubName,
|
||||
&n.Status, &n.CreatedAt,
|
||||
)
|
||||
if errN != nil {
|
||||
r.logger.Error("errN :::", errN)
|
||||
continue
|
||||
}
|
||||
|
||||
ns = append(ns, n)
|
||||
}
|
||||
dt.Categories = ns
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) GetData(ctx context.Context, id int) (category.CategoryDTO, error) {
|
||||
|
||||
var (
|
||||
ns category.CategoryDTO
|
||||
)
|
||||
|
||||
qC := `select id, name, status, created_at from categories where id = $1 ;`
|
||||
err := r.client.QueryRow(ctx, qC, id).Scan(&ns.Id, &ns.Name, &ns.Status, &ns.CreatedAt)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return ns, err
|
||||
}
|
||||
|
||||
return ns, nil
|
||||
}
|
||||
|
||||
func (r repository) AddData(ctx context.Context, req category.AddCategoryDTO) (category.CategoryIdDTO, error) {
|
||||
|
||||
var (
|
||||
n category.CategoryIdDTO
|
||||
)
|
||||
|
||||
q := `INSERT INTO categories (name) VALUES ($1) RETURNING id, name, status;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, req.Name).Scan(
|
||||
&n.Id, &n.Name, &n.Status,
|
||||
)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return n, err
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) UpdateData(ctx context.Context, req category.UpdateCategoryDTO, id int) (category.CategoryIdDTO, error) {
|
||||
var (
|
||||
q string
|
||||
n category.CategoryIdDTO
|
||||
)
|
||||
|
||||
q = ` update categories set name = $1 where Id = $2 RETURNING id, name, status;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, req.Name, id).Scan(
|
||||
&n.Id, &n.Name, &n.Status,
|
||||
)
|
||||
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return n, err
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) UpdateStatusData(ctx context.Context, status string, id int) (category.CategoryDTO, error) {
|
||||
|
||||
q := ` update categories set status = $1 where id = $2;`
|
||||
|
||||
_, err := r.client.Exec(ctx, q, status, id)
|
||||
|
||||
dt, err := r.GetData(ctx, id)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return dt, err
|
||||
}
|
||||
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) DeleteData(ctx context.Context, Id int) error {
|
||||
var (
|
||||
q string
|
||||
)
|
||||
|
||||
q = ` delete from categories where Id = $1 ;`
|
||||
_, err := r.client.Exec(ctx, q, Id)
|
||||
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
49
backend/internal/admin/category/dto.go
Executable file
49
backend/internal/admin/category/dto.go
Executable file
@@ -0,0 +1,49 @@
|
||||
package category
|
||||
|
||||
import "time"
|
||||
|
||||
type DataCategoryDTO struct {
|
||||
Categories []CategoryDTO `json:"categories"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type Language struct {
|
||||
Tm string `json:"tm"`
|
||||
Ru string `json:"ru"`
|
||||
En string `json:"en"`
|
||||
}
|
||||
|
||||
type CategoryDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Name Language `json:"name"`
|
||||
SubName []Language `json:"subCategories"`
|
||||
Status bool `json:"status"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type AddCategoryDTO struct {
|
||||
Name Language `json:"name" binding:"required"`
|
||||
}
|
||||
|
||||
type UpdateCategoryDTO struct {
|
||||
Name Language `json:"name" binding:"required"`
|
||||
// Status intentionally has no "required" binding: the validator treats
|
||||
// false as a missing value, which would make it impossible to update a
|
||||
// disabled category.
|
||||
Status bool `json:"status"`
|
||||
}
|
||||
|
||||
type CategoryIdDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Name Language `json:"name"`
|
||||
Status bool `json:"status"`
|
||||
}
|
||||
|
||||
type PaginationDTO struct {
|
||||
Limit int `json:"limit"`
|
||||
Page int `json:"page"`
|
||||
}
|
||||
|
||||
type ReqIdDTO struct {
|
||||
Id int `json:"Id"`
|
||||
}
|
||||
246
backend/internal/admin/category/handler.go
Executable file
246
backend/internal/admin/category/handler.go
Executable file
@@ -0,0 +1,246 @@
|
||||
package category
|
||||
|
||||
import (
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/handlers"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
getAllURL = ""
|
||||
getOneURL = "/:id"
|
||||
getStatusURL = "/:id/status"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
repository Repository
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewHandler(repository Repository, logger *logging.Logger) handlers.Handler {
|
||||
return &handler{
|
||||
repository: repository,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
router.GET(getAllURL, h.GetAll)
|
||||
router.GET(getOneURL, h.GetOne)
|
||||
|
||||
router.POST(getAllURL, h.Create)
|
||||
router.PUT(getOneURL, h.Update)
|
||||
router.PUT(getStatusURL, h.UpdateStatus)
|
||||
router.DELETE(getOneURL, h.Delete)
|
||||
|
||||
}
|
||||
|
||||
// GetAll godoc
|
||||
// @Description all data categories
|
||||
// @Tags categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param limit query int false "limit"
|
||||
// @Param page query int false "page"
|
||||
// @Param search query string false "search term"
|
||||
// @Param sort query string false "sort column (id, status, createdAt)"
|
||||
// @Param order query string false "sort order (asc, desc)"
|
||||
// @Success 200 {object} DataCategoryDTO
|
||||
// @Router /admin/categories [get]
|
||||
func (h *handler) GetAll(c *gin.Context) {
|
||||
result, err := h.repository.GetAllData(context.Background(), listing.FromQuery(c))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetOne godoc
|
||||
// @Description one data category
|
||||
// @Tags categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "category ID"
|
||||
// @Success 200 {object} CategoryDTO
|
||||
// @Router /admin/categories/{id} [get]
|
||||
func (h *handler) GetOne(c *gin.Context) {
|
||||
|
||||
categoryId := c.Param("id")
|
||||
id, err := strconv.Atoi(categoryId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.GetData(context.Background(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Create godoc
|
||||
// @Description create categories
|
||||
// @Tags categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param categories body AddCategoryDTO true "Create JSON"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/categories [post]
|
||||
func (h *handler) Create(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
reqDTO AddCategoryDTO
|
||||
)
|
||||
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.repository.AddData(context.Background(), reqDTO)
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Update godoc
|
||||
// @Description update categories
|
||||
// @Tags categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "category ID"
|
||||
// @Param categories body UpdateCategoryDTO true "Create JSON"
|
||||
// @Success 200 {object} CategoryIdDTO
|
||||
// @Router /admin/categories/{id} [put]
|
||||
func (h *handler) Update(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
reqDTO UpdateCategoryDTO
|
||||
res CategoryIdDTO
|
||||
)
|
||||
|
||||
categoryId := c.Param("id")
|
||||
id, err := strconv.Atoi(categoryId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("uuid :::", id)
|
||||
if id != 0 {
|
||||
res, err = h.repository.UpdateData(context.Background(), reqDTO, id)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
fmt.Println("err :::", err)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// UpdateStatus godoc
|
||||
// @Description update status categories
|
||||
// @Tags categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "category id"
|
||||
// @Param status query bool true "status"
|
||||
// @Success 200 {object} CategoryDTO
|
||||
// @Router /admin/categories/{id}/status [put]
|
||||
func (h *handler) UpdateStatus(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
res CategoryDTO
|
||||
)
|
||||
Id := c.Param("id")
|
||||
id, err := strconv.Atoi(Id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
status, _ := c.GetQuery("status")
|
||||
fmt.Println("id :::", id)
|
||||
if id != 0 {
|
||||
res, err = h.repository.UpdateStatusData(context.Background(), status, id)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Delete godoc
|
||||
// @Description delete category
|
||||
// @Tags categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "category ID"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/categories/{id} [delete]
|
||||
func (h *handler) Delete(c *gin.Context) {
|
||||
|
||||
categoryId := c.Param("id")
|
||||
id, err := strconv.Atoi(categoryId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.repository.DeleteData(context.Background(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = ""
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
1
backend/internal/admin/category/model.go
Executable file
1
backend/internal/admin/category/model.go
Executable file
@@ -0,0 +1 @@
|
||||
package category
|
||||
16
backend/internal/admin/category/storage.go
Executable file
16
backend/internal/admin/category/storage.go
Executable file
@@ -0,0 +1,16 @@
|
||||
package category
|
||||
|
||||
import (
|
||||
"bankline/internal/listing"
|
||||
"context"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
GetAllData(ctx context.Context, params listing.Params) (DataCategoryDTO, error)
|
||||
GetData(ctx context.Context, id int) (CategoryDTO, error)
|
||||
|
||||
AddData(ctx context.Context, dto AddCategoryDTO) (CategoryIdDTO, error)
|
||||
UpdateData(ctx context.Context, dto UpdateCategoryDTO, id int) (CategoryIdDTO, error)
|
||||
UpdateStatusData(ctx context.Context, status string, id int) (CategoryDTO, error)
|
||||
DeleteData(ctx context.Context, uuid int) error
|
||||
}
|
||||
167
backend/internal/admin/currency/db/postgresql.go
Normal file
167
backend/internal/admin/currency/db/postgresql.go
Normal file
@@ -0,0 +1,167 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/currency"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client *pgxpool.Pool
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client *pgxpool.Pool, logger *logging.Logger) currency.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
var sortColumns = map[string]string{
|
||||
"id": "id",
|
||||
"createdAt": "created_at",
|
||||
}
|
||||
|
||||
func (r repository) GetAllData(ctx context.Context, params listing.Params) (currency.DataCurrencyDTO, error) {
|
||||
|
||||
ns := []currency.CurrencyDTO{}
|
||||
var (
|
||||
dt currency.DataCurrencyDTO
|
||||
err error
|
||||
rows pgx.Rows
|
||||
)
|
||||
|
||||
where := ""
|
||||
args := []interface{}{}
|
||||
if params.Search != "" {
|
||||
where = ` where title::text ILIKE $1 or content_tm ILIKE $1 or content_ru ILIKE $1 or content_en ILIKE $1 `
|
||||
args = append(args, params.SearchPattern())
|
||||
}
|
||||
|
||||
qC := `select count(*) from currency` + where + `;`
|
||||
r.client.QueryRow(ctx, qC, args...).Scan(&dt.Count)
|
||||
|
||||
q := ` select
|
||||
id, title,
|
||||
content_tm, content_ru, content_en,
|
||||
path, created_at
|
||||
from currency` +
|
||||
where +
|
||||
params.OrderClause(sortColumns, "created_at DESC")
|
||||
|
||||
if params.Paginated() {
|
||||
q += fmt.Sprintf("limit $%d offset $%d;", len(args)+1, len(args)+2)
|
||||
args = append(args, params.Limit, params.Offset())
|
||||
} else {
|
||||
q += ";"
|
||||
}
|
||||
rows, err = r.client.Query(ctx, q, args...)
|
||||
if err != nil {
|
||||
return dt, nil
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var n currency.CurrencyDTO
|
||||
errN := rows.Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.ContentTm, &n.ContentRu, &n.ContentEn,
|
||||
&n.Path, &n.CreatedAt,
|
||||
)
|
||||
if errN != nil {
|
||||
r.logger.Error("errN :::", errN)
|
||||
continue
|
||||
}
|
||||
|
||||
ns = append(ns, n)
|
||||
}
|
||||
dt.Currencies = ns
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) GetData(ctx context.Context, id int) (currency.CurrencyDTO, error) {
|
||||
|
||||
var (
|
||||
ns currency.CurrencyDTO
|
||||
)
|
||||
|
||||
qC := `select id, title, content_tm, content_ru, content_en, path, created_at from currency where id = $1 ;`
|
||||
err := r.client.QueryRow(ctx, qC, id).Scan(
|
||||
&ns.Id, &ns.Title,
|
||||
&ns.ContentTm, &ns.ContentRu, &ns.ContentEn,
|
||||
&ns.Path, &ns.CreatedAt,
|
||||
)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return ns, err
|
||||
}
|
||||
|
||||
return ns, nil
|
||||
}
|
||||
|
||||
func (r repository) AddData(ctx context.Context, req currency.AddCurrencyDTO) (currency.CurrencyIdDTO, error) {
|
||||
|
||||
var (
|
||||
n currency.CurrencyIdDTO
|
||||
)
|
||||
|
||||
q := `INSERT INTO currency (title, content_tm, content_ru, content_en, path)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING id, title, path;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q,
|
||||
req.Title, req.ContentTm, req.ContentRu, req.ContentEn, req.Path,
|
||||
).Scan(
|
||||
&n.Id, &n.Title, &n.Path,
|
||||
)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return n, err
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) UpdateData(ctx context.Context, req currency.UpdateCurrencyDTO, id int) (currency.CurrencyIdDTO, error) {
|
||||
var (
|
||||
q string
|
||||
n currency.CurrencyIdDTO
|
||||
)
|
||||
|
||||
q = ` update currency set
|
||||
title = $1, content_tm = $2, content_ru = $3, content_en = $4, path = $5
|
||||
where id = $6
|
||||
RETURNING id, title, path;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q,
|
||||
req.Title, req.ContentTm, req.ContentRu, req.ContentEn, req.Path,
|
||||
id,
|
||||
).Scan(
|
||||
&n.Id, &n.Title, &n.Path,
|
||||
)
|
||||
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return n, err
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) DeleteData(ctx context.Context, id int) error {
|
||||
var (
|
||||
q string
|
||||
)
|
||||
|
||||
q = ` delete from currency where id = $1 ;`
|
||||
_, err := r.client.Exec(ctx, q, id)
|
||||
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
46
backend/internal/admin/currency/dto.go
Normal file
46
backend/internal/admin/currency/dto.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package currency
|
||||
|
||||
import "time"
|
||||
|
||||
type DataCurrencyDTO struct {
|
||||
Currencies []CurrencyDTO `json:"currencies"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type Language struct {
|
||||
Tm string `json:"tm"`
|
||||
Ru string `json:"ru"`
|
||||
En string `json:"en"`
|
||||
}
|
||||
|
||||
type CurrencyDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Title Language `json:"title"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
Path string `json:"path"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type AddCurrencyDTO struct {
|
||||
Title Language `json:"title" binding:"required"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
Path string `json:"path" binding:"required"`
|
||||
}
|
||||
|
||||
type UpdateCurrencyDTO struct {
|
||||
Title Language `json:"title" binding:"required"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
Path string `json:"path" binding:"required"`
|
||||
}
|
||||
|
||||
type CurrencyIdDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Title Language `json:"title"`
|
||||
Path string `json:"path"`
|
||||
}
|
||||
203
backend/internal/admin/currency/handler.go
Normal file
203
backend/internal/admin/currency/handler.go
Normal file
@@ -0,0 +1,203 @@
|
||||
package currency
|
||||
|
||||
import (
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/handlers"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
getAllURL = ""
|
||||
getOneURL = "/:id"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
repository Repository
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewHandler(repository Repository, logger *logging.Logger) handlers.Handler {
|
||||
return &handler{
|
||||
repository: repository,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
router.GET(getAllURL, h.GetAll)
|
||||
router.GET(getOneURL, h.GetOne)
|
||||
|
||||
router.POST(getAllURL, h.Create)
|
||||
router.PUT(getOneURL, h.Update)
|
||||
router.DELETE(getOneURL, h.Delete)
|
||||
|
||||
}
|
||||
|
||||
// GetAll godoc
|
||||
// @Description all data currencies
|
||||
// @Tags currencies
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param limit query int false "limit"
|
||||
// @Param page query int false "page"
|
||||
// @Param search query string false "search term"
|
||||
// @Param sort query string false "sort column (id, createdAt)"
|
||||
// @Param order query string false "sort order (asc, desc)"
|
||||
// @Success 200 {object} DataCurrencyDTO
|
||||
// @Router /admin/currency [get]
|
||||
func (h *handler) GetAll(c *gin.Context) {
|
||||
result, err := h.repository.GetAllData(context.Background(), listing.FromQuery(c))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetOne godoc
|
||||
// @Description one data currency
|
||||
// @Tags currencies
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "currency ID"
|
||||
// @Success 200 {object} CurrencyDTO
|
||||
// @Router /admin/currency/{id} [get]
|
||||
func (h *handler) GetOne(c *gin.Context) {
|
||||
|
||||
currencyId := c.Param("id")
|
||||
id, err := strconv.Atoi(currencyId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.GetData(context.Background(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Create godoc
|
||||
// @Description create currency
|
||||
// @Tags currencies
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param currency body AddCurrencyDTO true "Create JSON"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/currency [post]
|
||||
func (h *handler) Create(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
reqDTO AddCurrencyDTO
|
||||
)
|
||||
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.repository.AddData(context.Background(), reqDTO)
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Update godoc
|
||||
// @Description update currency
|
||||
// @Tags currencies
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "currency ID"
|
||||
// @Param currency body UpdateCurrencyDTO true "Create JSON"
|
||||
// @Success 200 {object} CurrencyIdDTO
|
||||
// @Router /admin/currency/{id} [put]
|
||||
func (h *handler) Update(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
reqDTO UpdateCurrencyDTO
|
||||
res CurrencyIdDTO
|
||||
)
|
||||
|
||||
currencyId := c.Param("id")
|
||||
id, err := strconv.Atoi(currencyId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if id != 0 {
|
||||
res, err = h.repository.UpdateData(context.Background(), reqDTO, id)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Delete godoc
|
||||
// @Description delete currency
|
||||
// @Tags currencies
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "currency ID"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/currency/{id} [delete]
|
||||
func (h *handler) Delete(c *gin.Context) {
|
||||
|
||||
currencyId := c.Param("id")
|
||||
id, err := strconv.Atoi(currencyId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.repository.DeleteData(context.Background(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = ""
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
15
backend/internal/admin/currency/storage.go
Normal file
15
backend/internal/admin/currency/storage.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package currency
|
||||
|
||||
import (
|
||||
"bankline/internal/listing"
|
||||
"context"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
GetAllData(ctx context.Context, params listing.Params) (DataCurrencyDTO, error)
|
||||
GetData(ctx context.Context, id int) (CurrencyDTO, error)
|
||||
|
||||
AddData(ctx context.Context, dto AddCurrencyDTO) (CurrencyIdDTO, error)
|
||||
UpdateData(ctx context.Context, dto UpdateCurrencyDTO, id int) (CurrencyIdDTO, error)
|
||||
DeleteData(ctx context.Context, id int) error
|
||||
}
|
||||
201
backend/internal/admin/news/db/postgresql.go
Executable file
201
backend/internal/admin/news/db/postgresql.go
Executable file
@@ -0,0 +1,201 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/news"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client *pgxpool.Pool
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client *pgxpool.Pool, logger *logging.Logger) news.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
var sortColumns = map[string]string{
|
||||
"id": "n.id",
|
||||
"dateRelease": "n.date_release",
|
||||
"createdAt": "n.created_at",
|
||||
}
|
||||
|
||||
func (r repository) GetAllData(ctx context.Context, params listing.Params) (news.DataNewsDTO, error) {
|
||||
var dt news.DataNewsDTO
|
||||
|
||||
where := ""
|
||||
args := []interface{}{}
|
||||
if params.Search != "" {
|
||||
where = ` WHERE n.title::text ILIKE $1 OR nc.tm ILIKE $1 OR nc.ru ILIKE $1 OR nc.en ILIKE $1 `
|
||||
args = append(args, params.SearchPattern())
|
||||
}
|
||||
|
||||
qC := `SELECT count(*) FROM news n LEFT JOIN news_content nc ON n.id = nc.news_id` + where + `;`
|
||||
if err := r.client.QueryRow(ctx, qC, args...).Scan(&dt.Count); err != nil {
|
||||
r.logger.Error("count news :::", err)
|
||||
return dt, err
|
||||
}
|
||||
|
||||
q := ` SELECT
|
||||
n.id, n.title,
|
||||
n.date_release, n.img,
|
||||
nc.en, nc.tm, nc.ru
|
||||
FROM news n
|
||||
LEFT JOIN news_content nc ON n.id = nc.news_id ` +
|
||||
where +
|
||||
params.OrderClause(sortColumns, "n.date_release DESC")
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if params.Paginated() {
|
||||
q += fmt.Sprintf("LIMIT $%d OFFSET $%d;", len(args)+1, len(args)+2)
|
||||
args = append(args, params.Limit, params.Offset())
|
||||
} else {
|
||||
q += ";"
|
||||
}
|
||||
rows, err = r.client.Query(ctx, q, args...)
|
||||
if err != nil {
|
||||
r.logger.Error("get all news :::", err)
|
||||
return dt, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
ns := []news.GetNewsDTO{}
|
||||
for rows.Next() {
|
||||
var n news.GetNewsDTO
|
||||
if err = rows.Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.DataRelease, &n.Image,
|
||||
&n.Content.En,
|
||||
&n.Content.Tm, &n.Content.Ru,
|
||||
); err != nil {
|
||||
r.logger.Error("scan news :::", err)
|
||||
continue
|
||||
}
|
||||
|
||||
ns = append(ns, n)
|
||||
}
|
||||
dt.Categories = ns
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) GetOneData(ctx context.Context, id int) (news.GetNewsDTO, error) {
|
||||
var n news.GetNewsDTO
|
||||
|
||||
q := ` SELECT
|
||||
n.id, n.title,
|
||||
n.date_release, n.img,
|
||||
nc.en, nc.tm, nc.ru
|
||||
FROM news n
|
||||
LEFT JOIN news_content nc ON n.id = nc.news_id
|
||||
WHERE n.id = $1; `
|
||||
|
||||
err := r.client.QueryRow(ctx, q, id).Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.DataRelease, &n.Image,
|
||||
&n.Content.En, &n.Content.Tm,
|
||||
&n.Content.Ru,
|
||||
)
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) AddData(ctx context.Context, req news.AddNewsDTO) (news.GetNewsDTO, error) {
|
||||
var (
|
||||
n news.GetNewsDTO
|
||||
lang news.Language
|
||||
)
|
||||
|
||||
q := `INSERT INTO news (title, img, date_release) VALUES ($1, $2, $3)
|
||||
RETURNING id, title, date_release, img;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, req.Title, req.Image, req.DataRelease).Scan(
|
||||
&n.Id, &n.Title, &n.DataRelease, &n.Image,
|
||||
)
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
r.logger.Error("add news :::", err)
|
||||
return n, err
|
||||
}
|
||||
if n.Id != 0 {
|
||||
q = `INSERT INTO news_content (news_id, en, ru, tm)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING en, ru, tm;`
|
||||
|
||||
err = r.client.QueryRow(ctx, q, n.Id, req.Content.En, req.Content.Ru, req.Content.Tm).Scan(
|
||||
&lang.En, &lang.Ru, &lang.Tm,
|
||||
)
|
||||
if err != nil {
|
||||
r.logger.Error("add news content :::", err)
|
||||
return n, err
|
||||
}
|
||||
n.Content = lang
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) UpdateData(ctx context.Context, req news.UpdateNewsDTO, id int) (news.GetNewsDTO, error) {
|
||||
var (
|
||||
n news.GetNewsDTO
|
||||
lang news.Language
|
||||
)
|
||||
|
||||
q := ` update news set
|
||||
title = $1, img = $2, date_release = $3
|
||||
where id = $4 RETURNING id, title, date_release, img;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q,
|
||||
req.Title, req.Image, req.DataRelease,
|
||||
id).Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.DataRelease, &n.Image,
|
||||
)
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
r.logger.Error("update news main :::", err)
|
||||
return n, err
|
||||
}
|
||||
if n.Id != 0 {
|
||||
q = ` UPDATE news_content SET en = $1, ru = $2, tm = $3 where news_id = $4 RETURNING en, ru, tm;`
|
||||
|
||||
err = r.client.QueryRow(ctx, q, req.Content.En, req.Content.Ru, req.Content.Tm, n.Id).Scan(&lang.En, &lang.Ru, &lang.Tm)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
q = `INSERT INTO news_content (news_id, en, ru, tm) VALUES ($1, $2, $3, $4) RETURNING en, ru, tm;`
|
||||
err = r.client.QueryRow(ctx, q, n.Id, req.Content.En, req.Content.Ru, req.Content.Tm).Scan(
|
||||
&lang.En, &lang.Ru, &lang.Tm,
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
r.logger.Error("update news content :::", err)
|
||||
return n, err
|
||||
}
|
||||
}
|
||||
n.Content = lang
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) DeleteData(ctx context.Context, id int) error {
|
||||
q := ` delete from news where id = $1 ;`
|
||||
_, err := r.client.Exec(ctx, q, id)
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
36
backend/internal/admin/news/dto.go
Executable file
36
backend/internal/admin/news/dto.go
Executable file
@@ -0,0 +1,36 @@
|
||||
package news
|
||||
|
||||
import "time"
|
||||
|
||||
type DataNewsDTO struct {
|
||||
Categories []GetNewsDTO `json:"news"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type GetNewsDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Title Language `json:"title"`
|
||||
Content Language `json:"content"`
|
||||
Image string `json:"imagePath"`
|
||||
DataRelease time.Time `json:"dateRelease"`
|
||||
}
|
||||
|
||||
type AddNewsDTO struct {
|
||||
Title Language `json:"title"`
|
||||
Content Language `json:"content"`
|
||||
Image string `json:"imagePath"`
|
||||
DataRelease time.Time `json:"dateRelease"`
|
||||
}
|
||||
|
||||
type UpdateNewsDTO struct {
|
||||
Title Language `json:"title"`
|
||||
Content Language `json:"content"`
|
||||
Image string `json:"imagePath"`
|
||||
DataRelease time.Time `json:"dateRelease"`
|
||||
}
|
||||
|
||||
type Language struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
177
backend/internal/admin/news/handler.go
Executable file
177
backend/internal/admin/news/handler.go
Executable file
@@ -0,0 +1,177 @@
|
||||
package news
|
||||
|
||||
import (
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/handlers"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
getAllURL = ""
|
||||
getOneURL = "/:id"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
repository Repository
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewHandler(repository Repository, logger *logging.Logger) handlers.Handler {
|
||||
return &handler{
|
||||
repository: repository,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
router.GET(getAllURL, h.GetAll)
|
||||
router.GET(getOneURL, h.GetOne)
|
||||
|
||||
router.POST(getAllURL, h.Create)
|
||||
router.PUT(getOneURL, h.Update)
|
||||
router.DELETE(getOneURL, h.Delete)
|
||||
}
|
||||
|
||||
// GetAll godoc
|
||||
// @Description all data news
|
||||
// @Tags news
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param limit query int false "limit"
|
||||
// @Param page query int false "page"
|
||||
// @Param search query string false "search term"
|
||||
// @Param sort query string false "sort column (id, dateRelease, createdAt)"
|
||||
// @Param order query string false "sort order (asc, desc)"
|
||||
// @Success 200 {object} DataNewsDTO
|
||||
// @Router /admin/news [get]
|
||||
func (h *handler) GetAll(c *gin.Context) {
|
||||
result, err := h.repository.GetAllData(c.Request.Context(), listing.FromQuery(c))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// GetOne godoc
|
||||
// @Description one data news
|
||||
// @Tags news
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "news ID"
|
||||
// @Success 200 {object} GetNewsDTO
|
||||
// @Router /admin/news/{id} [get]
|
||||
func (h *handler) GetOne(c *gin.Context) {
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.GetOneData(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// Create godoc
|
||||
// @Description create news
|
||||
// @Tags news
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param news body AddNewsDTO true "Create JSON"
|
||||
// @Success 200 {object} GetNewsDTO
|
||||
// @Router /admin/news [post]
|
||||
func (h *handler) Create(c *gin.Context) {
|
||||
var reqDTO AddNewsDTO
|
||||
if err := c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.repository.AddData(c.Request.Context(), reqDTO)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// Update godoc
|
||||
// @Description update news
|
||||
// @Tags news
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "news ID"
|
||||
// @Param news body UpdateNewsDTO true "Create JSON"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/news/{id} [put]
|
||||
func (h *handler) Update(c *gin.Context) {
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
var reqDTO UpdateNewsDTO
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.repository.UpdateData(c.Request.Context(), reqDTO, id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// Delete godoc
|
||||
// @Description delete news
|
||||
// @Tags news
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "news ID"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/news/{id} [delete]
|
||||
func (h *handler) Delete(c *gin.Context) {
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
if err = h.repository.DeleteData(c.Request.Context(), id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = ""
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
14
backend/internal/admin/news/storage.go
Executable file
14
backend/internal/admin/news/storage.go
Executable file
@@ -0,0 +1,14 @@
|
||||
package news
|
||||
|
||||
import (
|
||||
"bankline/internal/listing"
|
||||
"context"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
GetAllData(ctx context.Context, params listing.Params) (DataNewsDTO, error)
|
||||
GetOneData(ctx context.Context, id int) (GetNewsDTO, error)
|
||||
AddData(ctx context.Context, dto AddNewsDTO) (GetNewsDTO, error)
|
||||
UpdateData(ctx context.Context, dto UpdateNewsDTO, id int) (GetNewsDTO, error)
|
||||
DeleteData(ctx context.Context, id int) error
|
||||
}
|
||||
79
backend/internal/admin/setting/db/postgresql.go
Executable file
79
backend/internal/admin/setting/db/postgresql.go
Executable file
@@ -0,0 +1,79 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/setting"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client *pgxpool.Pool
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client *pgxpool.Pool, logger *logging.Logger) setting.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (r repository) GetData(ctx context.Context) (setting.SettingDTO, error) {
|
||||
q := `SELECT id, uuid::text, logo_r, phone_number, fax_number, help_number, created_at
|
||||
FROM setting ORDER BY id ASC LIMIT 1;`
|
||||
|
||||
var n setting.SettingDTO
|
||||
errN := r.client.QueryRow(ctx, q).Scan(
|
||||
&n.Id, &n.UUID, &n.LogoR, &n.PhoneNumber, &n.FaxNumber, &n.HelpNumber, &n.CreatedAt,
|
||||
)
|
||||
if errN != nil {
|
||||
if errN.Error() == "no rows in result set" {
|
||||
return n, nil
|
||||
}
|
||||
r.logger.Error("errN :::", errN)
|
||||
return n, errN
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) UpdateData(ctx context.Context, req setting.UpdateSettingDTO, id int) (setting.SettingDTO, error) {
|
||||
q := `UPDATE setting SET
|
||||
logo_r = $1,
|
||||
phone_number = $2,
|
||||
fax_number = $3,
|
||||
help_number = $4,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $5;`
|
||||
|
||||
tag, err := r.client.Exec(ctx, q, req.LogoR, req.PhoneNumber, req.FaxNumber, req.HelpNumber, id)
|
||||
if err != nil {
|
||||
return setting.SettingDTO{}, err
|
||||
}
|
||||
|
||||
if tag.RowsAffected() == 0 {
|
||||
// No matching row — insert (optionally with requested id).
|
||||
if id > 0 {
|
||||
q = `INSERT INTO setting (id, logo_r, phone_number, fax_number, help_number)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
logo_r = EXCLUDED.logo_r,
|
||||
phone_number = EXCLUDED.phone_number,
|
||||
fax_number = EXCLUDED.fax_number,
|
||||
help_number = EXCLUDED.help_number,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC');`
|
||||
_, err = r.client.Exec(ctx, q, id, req.LogoR, req.PhoneNumber, req.FaxNumber, req.HelpNumber)
|
||||
} else {
|
||||
q = `INSERT INTO setting (logo_r, phone_number, fax_number, help_number)
|
||||
VALUES ($1, $2, $3, $4);`
|
||||
_, err = r.client.Exec(ctx, q, req.LogoR, req.PhoneNumber, req.FaxNumber, req.HelpNumber)
|
||||
}
|
||||
if err != nil {
|
||||
return setting.SettingDTO{}, err
|
||||
}
|
||||
}
|
||||
|
||||
return r.GetData(ctx)
|
||||
}
|
||||
20
backend/internal/admin/setting/dto.go
Executable file
20
backend/internal/admin/setting/dto.go
Executable file
@@ -0,0 +1,20 @@
|
||||
package setting
|
||||
|
||||
import "time"
|
||||
|
||||
type SettingDTO struct {
|
||||
Id int `json:"Id"`
|
||||
UUID string `json:"UUID"`
|
||||
LogoR string `json:"logoR"`
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
FaxNumber string `json:"faxNumber"`
|
||||
HelpNumber string `json:"helpNumber"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type UpdateSettingDTO struct {
|
||||
LogoR string `json:"logoR"`
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
FaxNumber string `json:"faxNumber"`
|
||||
HelpNumber string `json:"helpNumber"`
|
||||
}
|
||||
94
backend/internal/admin/setting/handler.go
Executable file
94
backend/internal/admin/setting/handler.go
Executable file
@@ -0,0 +1,94 @@
|
||||
package setting
|
||||
|
||||
import (
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/handlers"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
getURL = ""
|
||||
addURL = "/:id"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
repository Repository
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewHandler(repository Repository, logger *logging.Logger) handlers.Handler {
|
||||
return &handler{
|
||||
repository: repository,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
router.GET(getURL, h.GetOne)
|
||||
router.POST(addURL, h.Create)
|
||||
}
|
||||
|
||||
// GetOne godoc
|
||||
// @Description get site setting
|
||||
// @Tags settings
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} SettingDTO
|
||||
// @Router /admin/setting [get]
|
||||
func (h *handler) GetOne(c *gin.Context) {
|
||||
result, err := h.repository.GetData(context.Background())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// Create godoc
|
||||
// @Description update site setting
|
||||
// @Tags settings
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param settings body UpdateSettingDTO true "Update JSON"
|
||||
// @Param id path int true "setting id"
|
||||
// @Success 200 {object} SettingDTO
|
||||
// @Router /admin/setting/{id} [post]
|
||||
func (h *handler) Create(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
reqDTO UpdateSettingDTO
|
||||
res SettingDTO
|
||||
)
|
||||
|
||||
Id := c.Param("id")
|
||||
id, err := strconv.Atoi(Id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
res, err = h.repository.UpdateData(context.Background(), reqDTO, id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
1
backend/internal/admin/setting/model.go
Executable file
1
backend/internal/admin/setting/model.go
Executable file
@@ -0,0 +1 @@
|
||||
package setting
|
||||
8
backend/internal/admin/setting/storage.go
Executable file
8
backend/internal/admin/setting/storage.go
Executable file
@@ -0,0 +1,8 @@
|
||||
package setting
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
GetData(ctx context.Context) (SettingDTO, error)
|
||||
UpdateData(ctx context.Context, dto UpdateSettingDTO, id int) (SettingDTO, error)
|
||||
}
|
||||
157
backend/internal/admin/static/db/postgresql.go
Normal file
157
backend/internal/admin/static/db/postgresql.go
Normal file
@@ -0,0 +1,157 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/static"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client *pgxpool.Pool
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client *pgxpool.Pool, logger *logging.Logger) static.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
var sortColumns = map[string]string{
|
||||
"id": "id",
|
||||
"createdAt": "created_at",
|
||||
}
|
||||
|
||||
func (r repository) GetAllData(ctx context.Context, params listing.Params) (static.DataStaticDTO, error) {
|
||||
|
||||
ns := []static.StaticDTO{}
|
||||
var (
|
||||
dt static.DataStaticDTO
|
||||
err error
|
||||
rows pgx.Rows
|
||||
)
|
||||
|
||||
where := ""
|
||||
args := []interface{}{}
|
||||
if params.Search != "" {
|
||||
where = ` where title::text ILIKE $1 or content_tm ILIKE $1 or content_ru ILIKE $1 or content_en ILIKE $1 `
|
||||
args = append(args, params.SearchPattern())
|
||||
}
|
||||
|
||||
qC := `select count(*) from static` + where + `;`
|
||||
r.client.QueryRow(ctx, qC, args...).Scan(&dt.Count)
|
||||
|
||||
q := ` select
|
||||
id, logo, title,
|
||||
content_tm, content_ru, content_en,
|
||||
created_at
|
||||
from static` +
|
||||
where +
|
||||
params.OrderClause(sortColumns, "created_at DESC")
|
||||
|
||||
if params.Paginated() {
|
||||
q += fmt.Sprintf("limit $%d offset $%d;", len(args)+1, len(args)+2)
|
||||
args = append(args, params.Limit, params.Offset())
|
||||
} else {
|
||||
q += ";"
|
||||
}
|
||||
rows, err = r.client.Query(ctx, q, args...)
|
||||
if err != nil {
|
||||
return dt, nil
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var n static.StaticDTO
|
||||
errN := rows.Scan(
|
||||
&n.Id, &n.Logo, &n.Title,
|
||||
&n.ContentTm, &n.ContentRu, &n.ContentEn,
|
||||
&n.CreatedAt,
|
||||
)
|
||||
if errN != nil {
|
||||
r.logger.Error("errN :::", errN)
|
||||
continue
|
||||
}
|
||||
|
||||
ns = append(ns, n)
|
||||
}
|
||||
dt.Statics = ns
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) GetData(ctx context.Context, id int) (static.StaticDTO, error) {
|
||||
|
||||
var (
|
||||
ns static.StaticDTO
|
||||
)
|
||||
|
||||
qC := `select id, logo, title, content_tm, content_ru, content_en, created_at from static where id = $1 ;`
|
||||
err := r.client.QueryRow(ctx, qC, id).Scan(
|
||||
&ns.Id, &ns.Logo, &ns.Title,
|
||||
&ns.ContentTm, &ns.ContentRu, &ns.ContentEn,
|
||||
&ns.CreatedAt,
|
||||
)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return ns, err
|
||||
}
|
||||
|
||||
return ns, nil
|
||||
}
|
||||
|
||||
func (r repository) AddData(ctx context.Context, req static.AddStaticDTO) (static.StaticIdDTO, error) {
|
||||
|
||||
var (
|
||||
n static.StaticIdDTO
|
||||
)
|
||||
|
||||
q := `INSERT INTO static (logo, title, content_tm, content_ru, content_en) VALUES ($1, $2, $3, $4, $5) RETURNING id, logo, title;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, req.Logo, req.Title, req.ContentTm, req.ContentRu, req.ContentEn).Scan(
|
||||
&n.Id, &n.Logo, &n.Title,
|
||||
)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return n, err
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) UpdateData(ctx context.Context, req static.UpdateStaticDTO, id int) (static.StaticIdDTO, error) {
|
||||
var (
|
||||
q string
|
||||
n static.StaticIdDTO
|
||||
)
|
||||
|
||||
q = ` update static set logo = $1, title = $2, content_tm = $3, content_ru = $4, content_en = $5 where id = $6 RETURNING id, logo, title;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, req.Logo, req.Title, req.ContentTm, req.ContentRu, req.ContentEn, id).Scan(
|
||||
&n.Id, &n.Logo, &n.Title,
|
||||
)
|
||||
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return n, err
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) DeleteData(ctx context.Context, id int) error {
|
||||
var (
|
||||
q string
|
||||
)
|
||||
|
||||
q = ` delete from static where id = $1 ;`
|
||||
_, err := r.client.Exec(ctx, q, id)
|
||||
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
55
backend/internal/admin/static/dto.go
Normal file
55
backend/internal/admin/static/dto.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package static
|
||||
|
||||
import "time"
|
||||
|
||||
type DataStaticDTO struct {
|
||||
Statics []StaticDTO `json:"statics"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type Language struct {
|
||||
Tm string `json:"tm"`
|
||||
Ru string `json:"ru"`
|
||||
En string `json:"en"`
|
||||
}
|
||||
|
||||
type StaticDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Logo string `json:"logo"`
|
||||
Title Language `json:"title"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type AddStaticDTO struct {
|
||||
Logo string `json:"logo" binding:"required"`
|
||||
Title Language `json:"title" binding:"required"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
}
|
||||
|
||||
type UpdateStaticDTO struct {
|
||||
Logo string `json:"logo" binding:"required"`
|
||||
Title Language `json:"title" binding:"required"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
}
|
||||
|
||||
type StaticIdDTO struct {
|
||||
Id int `json:"Id"`
|
||||
Logo string `json:"logo"`
|
||||
Title Language `json:"title"`
|
||||
}
|
||||
|
||||
type PaginationDTO struct {
|
||||
Limit int `json:"limit"`
|
||||
Page int `json:"page"`
|
||||
}
|
||||
|
||||
type ReqIdDTO struct {
|
||||
Id int `json:"Id"`
|
||||
}
|
||||
206
backend/internal/admin/static/handler.go
Normal file
206
backend/internal/admin/static/handler.go
Normal file
@@ -0,0 +1,206 @@
|
||||
package static
|
||||
|
||||
import (
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/handlers"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
getAllURL = ""
|
||||
getOneURL = "/:id"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
repository Repository
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewHandler(repository Repository, logger *logging.Logger) handlers.Handler {
|
||||
return &handler{
|
||||
repository: repository,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
router.GET(getAllURL, h.GetAll)
|
||||
router.GET(getOneURL, h.GetOne)
|
||||
|
||||
router.POST(getAllURL, h.Create)
|
||||
router.PUT(getOneURL, h.Update)
|
||||
router.DELETE(getOneURL, h.Delete)
|
||||
|
||||
}
|
||||
|
||||
// GetAll godoc
|
||||
// @Description all data statics
|
||||
// @Tags statics
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param limit query int false "limit"
|
||||
// @Param page query int false "page"
|
||||
// @Param search query string false "search term"
|
||||
// @Param sort query string false "sort column (id, createdAt)"
|
||||
// @Param order query string false "sort order (asc, desc)"
|
||||
// @Success 200 {object} DataStaticDTO
|
||||
// @Router /admin/static [get]
|
||||
func (h *handler) GetAll(c *gin.Context) {
|
||||
result, err := h.repository.GetAllData(context.Background(), listing.FromQuery(c))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetOne godoc
|
||||
// @Description one data static
|
||||
// @Tags statics
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "static ID"
|
||||
// @Success 200 {object} StaticDTO
|
||||
// @Router /admin/static/{id} [get]
|
||||
func (h *handler) GetOne(c *gin.Context) {
|
||||
|
||||
staticId := c.Param("id")
|
||||
id, err := strconv.Atoi(staticId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.GetData(context.Background(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Create godoc
|
||||
// @Description create statics
|
||||
// @Tags statics
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param statics body AddStaticDTO true "Create JSON"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/static [post]
|
||||
func (h *handler) Create(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
reqDTO AddStaticDTO
|
||||
)
|
||||
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.repository.AddData(context.Background(), reqDTO)
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Update godoc
|
||||
// @Description update statics
|
||||
// @Tags statics
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "static ID"
|
||||
// @Param statics body UpdateStaticDTO true "Create JSON"
|
||||
// @Success 200 {object} StaticIdDTO
|
||||
// @Router /admin/static/{id} [put]
|
||||
func (h *handler) Update(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
reqDTO UpdateStaticDTO
|
||||
res StaticIdDTO
|
||||
)
|
||||
|
||||
staticId := c.Param("id")
|
||||
id, err := strconv.Atoi(staticId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("uuid :::", id)
|
||||
if id != 0 {
|
||||
res, err = h.repository.UpdateData(context.Background(), reqDTO, id)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
fmt.Println("err :::", err)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Delete godoc
|
||||
// @Description delete static
|
||||
// @Tags statics
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "static ID"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/static/{id} [delete]
|
||||
func (h *handler) Delete(c *gin.Context) {
|
||||
|
||||
staticId := c.Param("id")
|
||||
id, err := strconv.Atoi(staticId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.repository.DeleteData(context.Background(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = ""
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
15
backend/internal/admin/static/storage.go
Normal file
15
backend/internal/admin/static/storage.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package static
|
||||
|
||||
import (
|
||||
"bankline/internal/listing"
|
||||
"context"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
GetAllData(ctx context.Context, params listing.Params) (DataStaticDTO, error)
|
||||
GetData(ctx context.Context, id int) (StaticDTO, error)
|
||||
|
||||
AddData(ctx context.Context, dto AddStaticDTO) (StaticIdDTO, error)
|
||||
UpdateData(ctx context.Context, dto UpdateStaticDTO, id int) (StaticIdDTO, error)
|
||||
DeleteData(ctx context.Context, id int) error
|
||||
}
|
||||
224
backend/internal/admin/sub_category/db/postgresql.go
Executable file
224
backend/internal/admin/sub_category/db/postgresql.go
Executable file
@@ -0,0 +1,224 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/sub_category"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client *pgxpool.Pool
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client *pgxpool.Pool, logger *logging.Logger) sub_category.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
var sortColumns = map[string]string{
|
||||
"id": "sc.id",
|
||||
"status": "sc.status",
|
||||
"createdAt": "sc.created_at",
|
||||
}
|
||||
|
||||
func (r repository) GetAllData(ctx context.Context, params listing.Params, categoryId int) (sub_category.DataDTO, error) {
|
||||
|
||||
ns := []sub_category.SubCategoryDTO{}
|
||||
var (
|
||||
dt sub_category.DataDTO
|
||||
err error
|
||||
rows pgx.Rows
|
||||
)
|
||||
|
||||
where := ` where sc.category_id = $1 `
|
||||
args := []interface{}{categoryId}
|
||||
if params.Search != "" {
|
||||
where += ` and (sc.name::text ILIKE $2 OR scc.tm ILIKE $2 OR scc.ru ILIKE $2 OR scc.en ILIKE $2) `
|
||||
args = append(args, params.SearchPattern())
|
||||
}
|
||||
|
||||
qC := `select count(sc.*) from sub_categories sc
|
||||
LEFT JOIN sub_categories_content scc ON sc.id = scc.sub_category_id` + where + `;`
|
||||
r.client.QueryRow(ctx, qC, args...).Scan(&dt.Count)
|
||||
|
||||
q := `select
|
||||
sc.id, sc.status,
|
||||
sc.name, sc.created_at,
|
||||
COALESCE(scc.en, ''), COALESCE(scc.tm, ''), COALESCE(scc.ru, '')
|
||||
from sub_categories sc
|
||||
LEFT JOIN sub_categories_content scc ON sc.id = scc.sub_category_id` +
|
||||
where +
|
||||
params.OrderClause(sortColumns, "sc.created_at DESC")
|
||||
|
||||
if params.Paginated() {
|
||||
q += fmt.Sprintf("limit $%d offset $%d;", len(args)+1, len(args)+2)
|
||||
args = append(args, params.Limit, params.Offset())
|
||||
} else {
|
||||
q += ";"
|
||||
}
|
||||
rows, err = r.client.Query(ctx, q, args...)
|
||||
if err != nil {
|
||||
fmt.Println("=========", err)
|
||||
return dt, nil
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var n sub_category.SubCategoryDTO
|
||||
errN := rows.Scan(
|
||||
&n.Id, &n.Status,
|
||||
&n.Name, &n.CreatedAt,
|
||||
&n.Content.En, &n.Content.Tm, &n.Content.Ru,
|
||||
)
|
||||
if errN != nil {
|
||||
fmt.Println("errN :::", errN)
|
||||
continue
|
||||
}
|
||||
|
||||
ns = append(ns, n)
|
||||
}
|
||||
dt.SubCategories = ns
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) GetData(ctx context.Context, id int) (sub_category.SubCategoryDTO, error) {
|
||||
|
||||
var (
|
||||
ns sub_category.SubCategoryDTO
|
||||
)
|
||||
|
||||
qC := `select
|
||||
sc.id, sc.category_id, sc.name, sc.status, sc.created_at,
|
||||
COALESCE(scc.en, ''), COALESCE(scc.tm, ''), COALESCE(scc.ru, '')
|
||||
from sub_categories sc
|
||||
LEFT JOIN sub_categories_content scc ON sc.id = scc.sub_category_id
|
||||
where sc.id = $1 ;`
|
||||
err := r.client.QueryRow(ctx, qC, id).Scan(
|
||||
&ns.Id, &ns.CatId, &ns.Name, &ns.Status, &ns.CreatedAt,
|
||||
&ns.Content.En, &ns.Content.Tm, &ns.Content.Ru,
|
||||
)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return ns, err
|
||||
}
|
||||
|
||||
return ns, nil
|
||||
}
|
||||
|
||||
func (r repository) AddData(ctx context.Context, req sub_category.AddSubCategoryDTO) (sub_category.SubCategoryDTO, error) {
|
||||
|
||||
var (
|
||||
n sub_category.SubCategoryDTO
|
||||
lang sub_category.Language
|
||||
)
|
||||
|
||||
q := `INSERT INTO sub_categories (category_id, name) VALUES ($1, $2) RETURNING id, category_id, name, status;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, req.CatId, req.Name).Scan(
|
||||
&n.Id, &n.CatId,
|
||||
&n.Name, &n.Status,
|
||||
)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
fmt.Println("-----------", err)
|
||||
return n, err
|
||||
}
|
||||
|
||||
if n.Id != 0 {
|
||||
q = `INSERT INTO sub_categories_content (sub_category_id, en, ru, tm)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING en, ru, tm;`
|
||||
|
||||
err = r.client.QueryRow(ctx, q, n.Id, req.Content.En, req.Content.Ru, req.Content.Tm).Scan(
|
||||
&lang.En, &lang.Ru, &lang.Tm,
|
||||
)
|
||||
if err != nil {
|
||||
fmt.Println("-----------", err)
|
||||
return n, err
|
||||
}
|
||||
n.Content = lang
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) UpdateData(ctx context.Context, req sub_category.UpdateSubCategoryDTO, id int) (sub_category.SubCategoryDTO, error) {
|
||||
var (
|
||||
q string
|
||||
n sub_category.SubCategoryDTO
|
||||
lang sub_category.Language
|
||||
)
|
||||
|
||||
q = ` update sub_categories set category_id = $1, name = $2 where Id = $3 RETURNING id, category_id, name, status;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, req.CatId, req.Name, id).Scan(
|
||||
&n.Id, &n.CatId,
|
||||
&n.Name, &n.Status,
|
||||
)
|
||||
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
fmt.Println("-----------", err)
|
||||
return n, err
|
||||
}
|
||||
|
||||
if n.Id != 0 {
|
||||
q = `UPDATE sub_categories_content SET en = $1, ru = $2, tm = $3
|
||||
WHERE sub_category_id = $4 RETURNING en, ru, tm;`
|
||||
|
||||
err = r.client.QueryRow(ctx, q, req.Content.En, req.Content.Ru, req.Content.Tm, n.Id).Scan(
|
||||
&lang.En, &lang.Ru, &lang.Tm,
|
||||
)
|
||||
if err != nil {
|
||||
// Row may be missing on older data — insert then.
|
||||
if err.Error() == "no rows in result set" {
|
||||
q = `INSERT INTO sub_categories_content (sub_category_id, en, ru, tm)
|
||||
VALUES ($1, $2, $3, $4) RETURNING en, ru, tm;`
|
||||
err = r.client.QueryRow(ctx, q, n.Id, req.Content.En, req.Content.Ru, req.Content.Tm).Scan(
|
||||
&lang.En, &lang.Ru, &lang.Tm,
|
||||
)
|
||||
}
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
fmt.Println("-----------", err)
|
||||
return n, err
|
||||
}
|
||||
}
|
||||
n.Content = lang
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r repository) UpdateStatusData(ctx context.Context, status string, id int) (sub_category.SubCategoryDTO, error) {
|
||||
|
||||
q := ` update sub_categories set status = $1 where id = $2;`
|
||||
|
||||
_, err := r.client.Exec(ctx, q, status, id)
|
||||
|
||||
dt, err := r.GetData(ctx, id)
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return dt, err
|
||||
}
|
||||
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) DeleteData(ctx context.Context, Id int) error {
|
||||
var (
|
||||
q string
|
||||
)
|
||||
|
||||
q = ` delete from sub_categories where Id = $1 ;`
|
||||
_, err := r.client.Exec(ctx, q, Id)
|
||||
|
||||
if err != nil && err.Error() != "no rows in result set" {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
35
backend/internal/admin/sub_category/dto.go
Executable file
35
backend/internal/admin/sub_category/dto.go
Executable file
@@ -0,0 +1,35 @@
|
||||
package sub_category
|
||||
|
||||
import "time"
|
||||
|
||||
type DataDTO struct {
|
||||
SubCategories []SubCategoryDTO `json:"subCategory"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type Language struct {
|
||||
Tm string `json:"tm"`
|
||||
Ru string `json:"ru"`
|
||||
En string `json:"en"`
|
||||
}
|
||||
|
||||
type SubCategoryDTO struct {
|
||||
Id int `json:"Id"`
|
||||
CatId int `json:"categoryId"`
|
||||
Name Language `json:"name"`
|
||||
Content Language `json:"content"`
|
||||
Status bool `json:"status"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type AddSubCategoryDTO struct {
|
||||
CatId int `json:"categoryId"`
|
||||
Name Language `json:"name"`
|
||||
Content Language `json:"content"`
|
||||
}
|
||||
|
||||
type UpdateSubCategoryDTO struct {
|
||||
CatId int `json:"categoryId"`
|
||||
Name Language `json:"name"`
|
||||
Content Language `json:"content"`
|
||||
}
|
||||
264
backend/internal/admin/sub_category/handler.go
Executable file
264
backend/internal/admin/sub_category/handler.go
Executable file
@@ -0,0 +1,264 @@
|
||||
package sub_category
|
||||
|
||||
import (
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/handlers"
|
||||
"bankline/internal/listing"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/go-playground/validator/v10"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
getAllURL = ""
|
||||
getOneURL = "/:id"
|
||||
getEditURL = "/:id/edit"
|
||||
getStatusURL = "/:id/status"
|
||||
)
|
||||
|
||||
var validate *validator.Validate
|
||||
|
||||
type handler struct {
|
||||
repository Repository
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewHandler(repository Repository, logger *logging.Logger) handlers.Handler {
|
||||
return &handler{
|
||||
repository: repository,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
router.GET(getOneURL, h.GetAll)
|
||||
router.GET(getEditURL, h.GetOne)
|
||||
router.POST(getAllURL, h.Create)
|
||||
|
||||
router.PUT(getOneURL, h.Update)
|
||||
router.PUT(getStatusURL, h.UpdateStatus)
|
||||
router.DELETE(getOneURL, h.Delete)
|
||||
}
|
||||
|
||||
// GetAll godoc
|
||||
// @Description all sub-categories
|
||||
// @Tags sub-categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param limit query int false "limit"
|
||||
// @Param page query int false "page"
|
||||
// @Param search query string false "search term"
|
||||
// @Param sort query string false "sort column (id, status, createdAt)"
|
||||
// @Param order query string false "sort order (asc, desc)"
|
||||
// @Param id path int true "category id"
|
||||
// @Success 200 {object} DataDTO
|
||||
// @Router /admin/sub-categories/{id} [get]
|
||||
func (h *handler) GetAll(c *gin.Context) {
|
||||
categoryId := c.Param("id")
|
||||
|
||||
id, err := strconv.Atoi(categoryId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.GetAllData(context.Background(), listing.FromQuery(c), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// GetOne godoc
|
||||
// @Description one data category
|
||||
// @Tags sub-categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "sub-category id"
|
||||
// @Success 200 {object} SubCategoryDTO
|
||||
// @Router /admin/sub-categories/{id}/edit [get]
|
||||
func (h *handler) GetOne(c *gin.Context) {
|
||||
|
||||
categoryId := c.Param("id")
|
||||
id, err := strconv.Atoi(categoryId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.GetData(context.Background(), id)
|
||||
if err != nil {
|
||||
appresult.ErrInternalServer.Err = err
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Create godoc
|
||||
// @Description create sub categories
|
||||
// @Tags sub-categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param sub-categories body AddSubCategoryDTO true "Create JSON"
|
||||
// @Success 200 {object} SubCategoryDTO
|
||||
// @Router /admin/sub-categories [post]
|
||||
func (h *handler) Create(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
reqDTO AddSubCategoryDTO
|
||||
)
|
||||
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
appresult.ErrMissingParam.Err = err
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := h.repository.AddData(context.Background(), reqDTO)
|
||||
|
||||
if err != nil {
|
||||
appresult.ErrInternalServer.Err = err
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Update godoc
|
||||
// @Description update sub categories
|
||||
// @Tags sub-categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "sub-category id"
|
||||
// @Param sub-categories body UpdateSubCategoryDTO true "Create JSON"
|
||||
// @Success 200 {object} SubCategoryDTO
|
||||
// @Router /admin/sub-categories/{id} [put]
|
||||
func (h *handler) Update(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
reqDTO UpdateSubCategoryDTO
|
||||
res SubCategoryDTO
|
||||
)
|
||||
|
||||
categoryId := c.Param("id")
|
||||
id, err := strconv.Atoi(categoryId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err = c.ShouldBindJSON(&reqDTO); err != nil {
|
||||
appresult.ErrNotFound.Err = err
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("uuid :::", id)
|
||||
if id != 0 {
|
||||
res, err = h.repository.UpdateData(context.Background(), reqDTO, id)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
appresult.ErrInternalServer.Err = err
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// UpdateStatus godoc
|
||||
// @Description update status sub-categories
|
||||
// @Tags sub-categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "sub-category id"
|
||||
// @Param status query bool true "status"
|
||||
// @Success 200 {object} SubCategoryDTO
|
||||
// @Router /admin/sub-categories/{id}/status [put]
|
||||
func (h *handler) UpdateStatus(c *gin.Context) {
|
||||
var (
|
||||
err error
|
||||
res SubCategoryDTO
|
||||
)
|
||||
Id := c.Param("id")
|
||||
id, err := strconv.Atoi(Id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
status, _ := c.GetQuery("status")
|
||||
fmt.Println("id :::", id)
|
||||
if id != 0 {
|
||||
res, err = h.repository.UpdateStatusData(context.Background(), status, id)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = res
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
|
||||
// Delete godoc
|
||||
// @Description delete sub-category
|
||||
// @Tags sub-categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "sub category id"
|
||||
// @Success 200 {string} string
|
||||
// @Router /admin/sub-categories/{id} [delete]
|
||||
func (h *handler) Delete(c *gin.Context) {
|
||||
|
||||
categoryId := c.Param("id")
|
||||
id, err := strconv.Atoi(categoryId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
err = h.repository.DeleteData(context.Background(), id)
|
||||
if err != nil {
|
||||
appresult.ErrInternalServer.Err = err
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = ""
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
return
|
||||
}
|
||||
1
backend/internal/admin/sub_category/model.go
Executable file
1
backend/internal/admin/sub_category/model.go
Executable file
@@ -0,0 +1 @@
|
||||
package sub_category
|
||||
15
backend/internal/admin/sub_category/storage.go
Executable file
15
backend/internal/admin/sub_category/storage.go
Executable file
@@ -0,0 +1,15 @@
|
||||
package sub_category
|
||||
|
||||
import (
|
||||
"bankline/internal/listing"
|
||||
"context"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
GetAllData(ctx context.Context, params listing.Params, categoryId int) (DataDTO, error)
|
||||
GetData(ctx context.Context, id int) (SubCategoryDTO, error)
|
||||
AddData(ctx context.Context, dto AddSubCategoryDTO) (SubCategoryDTO, error)
|
||||
UpdateData(ctx context.Context, dto UpdateSubCategoryDTO, id int) (SubCategoryDTO, error)
|
||||
UpdateStatusData(ctx context.Context, status string, id int) (SubCategoryDTO, error)
|
||||
DeleteData(ctx context.Context, id int) error
|
||||
}
|
||||
104
backend/internal/admin/ui/handler.go
Normal file
104
backend/internal/admin/ui/handler.go
Normal file
@@ -0,0 +1,104 @@
|
||||
// Package ui serves the admin dashboard pages at /admin.
|
||||
// Pages are template shells; all data is fetched client-side from the
|
||||
// existing JWT-protected /v1/admin API.
|
||||
package ui
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Resource describes an admin CRUD resource rendered by the generic
|
||||
// list/form templates. Slug is both the URL segment and the key used by
|
||||
// the client-side schema in resources.js.
|
||||
type Resource struct {
|
||||
Slug string
|
||||
Title string
|
||||
}
|
||||
|
||||
var resources = []Resource{
|
||||
{Slug: "categories", Title: "Categories"},
|
||||
{Slug: "sub-categories", Title: "Sub-categories"},
|
||||
{Slug: "banners", Title: "Banners"},
|
||||
{Slug: "news", Title: "News"},
|
||||
{Slug: "static", Title: "Static pages"},
|
||||
{Slug: "currency", Title: "Currency rates"},
|
||||
}
|
||||
|
||||
// Register mounts templates, static assets and all dashboard page routes.
|
||||
func Register(router *gin.Engine) {
|
||||
router.LoadHTMLGlob("web/admin/templates/**/*.html")
|
||||
router.Static("/admin/assets", "./web/admin/assets")
|
||||
|
||||
admin := router.Group("/admin")
|
||||
|
||||
admin.GET("/login", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "pages/login", gin.H{
|
||||
"Title": "Login",
|
||||
"Page": "login",
|
||||
})
|
||||
})
|
||||
|
||||
admin.GET("", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "pages/dashboard", gin.H{
|
||||
"Title": "Dashboard",
|
||||
"Page": "dashboard",
|
||||
"Active": "dashboard",
|
||||
})
|
||||
})
|
||||
|
||||
admin.GET("/settings", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "pages/settings", gin.H{
|
||||
"Title": "Settings",
|
||||
"Page": "settings",
|
||||
"Active": "settings",
|
||||
})
|
||||
})
|
||||
|
||||
for _, res := range resources {
|
||||
res := res
|
||||
|
||||
admin.GET("/"+res.Slug, func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "pages/list", gin.H{
|
||||
"Title": res.Title,
|
||||
"Page": "list",
|
||||
"Active": res.Slug,
|
||||
"Resource": res.Slug,
|
||||
})
|
||||
})
|
||||
|
||||
admin.GET("/"+res.Slug+"/new", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "pages/form", gin.H{
|
||||
"Title": "New — " + res.Title,
|
||||
"Page": "form",
|
||||
"Active": res.Slug,
|
||||
"Resource": res.Slug,
|
||||
"Mode": "create",
|
||||
})
|
||||
})
|
||||
|
||||
admin.GET("/"+res.Slug+"/:id/edit", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "pages/form", gin.H{
|
||||
"Title": "Edit — " + res.Title,
|
||||
"Page": "form",
|
||||
"Active": res.Slug,
|
||||
"Resource": res.Slug,
|
||||
"Mode": "edit",
|
||||
"Id": c.Param("id"),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
router.NoRoute(func(c *gin.Context) {
|
||||
if strings.HasPrefix(c.Request.URL.Path, "/admin") {
|
||||
c.HTML(http.StatusNotFound, "pages/404", gin.H{
|
||||
"Title": "Page not found",
|
||||
"Page": "404",
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusNotFound, gin.H{"status": false, "message": "not found"})
|
||||
})
|
||||
}
|
||||
48
backend/internal/appresult/error.go
Executable file
48
backend/internal/appresult/error.go
Executable file
@@ -0,0 +1,48 @@
|
||||
package appresult
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
var (
|
||||
ErrMissingParam = NewAppError(nil, "missing param", "SE-00001")
|
||||
ErrNotFound = NewAppError(nil, "not found", "SE-00003")
|
||||
ErrInternalServer = NewAppError(nil, "internal server error", "SE-00004")
|
||||
ErrNotAcceptable = NewAppError(nil, "Not acceptable", "SE-00007")
|
||||
ErrCheckPasswordLimitFull = NewAppError(nil, "ErrCheckPasswordLimitFull", "SE-00008")
|
||||
ErrUpdatePassword = NewAppError(nil, "missing password", "SE-00010")
|
||||
ErrCheckEmail = NewAppError(nil, "Please enter a valid email address", "SE-00011")
|
||||
ErrAccount = NewAppError(nil, "This account has already been registered", "SE-00015")
|
||||
)
|
||||
|
||||
type AppError struct {
|
||||
Status bool `json:"status"`
|
||||
Err error `json:"err,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
}
|
||||
|
||||
func (e *AppError) Error() string {
|
||||
return e.Message
|
||||
}
|
||||
|
||||
func (e *AppError) Unwrap() error { return e.Err }
|
||||
|
||||
func (e *AppError) Marshal() []byte {
|
||||
marshal, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return marshal
|
||||
}
|
||||
|
||||
func NewAppError(err error, message, code string) *AppError {
|
||||
return &AppError{
|
||||
Status: false,
|
||||
Err: err,
|
||||
Message: message,
|
||||
Code: code,
|
||||
}
|
||||
}
|
||||
|
||||
func systemError(err error) *AppError {
|
||||
return NewAppError(err, "internal system error", "SE-000")
|
||||
}
|
||||
78
backend/internal/appresult/middleware.go
Executable file
78
backend/internal/appresult/middleware.go
Executable file
@@ -0,0 +1,78 @@
|
||||
package appresult
|
||||
|
||||
import (
|
||||
"bankline/internal/config"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type UnsignedResponse struct {
|
||||
Message interface{} `json:"message"`
|
||||
}
|
||||
|
||||
type appHandler func(w http.ResponseWriter, r *http.Request) error
|
||||
|
||||
func HeaderContentTypeJson() (string, string) {
|
||||
return "Content-Type", "application/json"
|
||||
}
|
||||
func AccessControlAllow() (string, string) {
|
||||
return "Access-Control-Allow-Origin", "*"
|
||||
}
|
||||
|
||||
func respondWithError(c *gin.Context, code int, message interface{}) {
|
||||
c.AbortWithStatusJSON(code, gin.H{"error": message})
|
||||
}
|
||||
|
||||
func JwtTokenCheck() gin.HandlerFunc {
|
||||
|
||||
return func(c *gin.Context) {
|
||||
token := c.GetHeader("Authorization")
|
||||
|
||||
if token == "" {
|
||||
respondWithError(c, 403, "Authorization header is missing")
|
||||
return
|
||||
}
|
||||
|
||||
cfg := config.GetConfig()
|
||||
claims, err := TokenClaims(token, cfg.JwtKey)
|
||||
if err != nil {
|
||||
respondWithError(c, 401, "Token is expired")
|
||||
return
|
||||
}
|
||||
|
||||
isAdmin := claims["admin"].(bool)
|
||||
if isAdmin == false {
|
||||
respondWithError(c, 403, "Unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("id", fmt.Sprint(claims["id"]))
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func TokenClaims(token, secretKey string) (jwt.MapClaims, error) {
|
||||
decoded, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
|
||||
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(secretKey), nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
fmt.Println("err", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
claims, ok := decoded.Claims.(jwt.MapClaims)
|
||||
|
||||
if !ok {
|
||||
// TODO tokenin omrini test etmeli
|
||||
return nil, ErrInternalServer
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
42
backend/internal/appresult/success.go
Executable file
42
backend/internal/appresult/success.go
Executable file
@@ -0,0 +1,42 @@
|
||||
package appresult
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
var (
|
||||
Success = NewAppSuccess("Success !!!", "SS-10000", nil)
|
||||
SuccessRegister = NewAppSuccess("You don't have an account.Please sign up", "SS-11000", nil)
|
||||
SuccessLogin = NewAppSuccess("you have an account !!!", "SS-12000", nil)
|
||||
)
|
||||
|
||||
type AppSuccess struct {
|
||||
Status bool `json:"status"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
Data interface{} `json:"data"`
|
||||
}
|
||||
|
||||
func (s *AppSuccess) Error() string {
|
||||
//TODO implement me
|
||||
panic("implement me")
|
||||
}
|
||||
|
||||
func (s *AppSuccess) Success() string {
|
||||
return s.Message
|
||||
}
|
||||
|
||||
func (s *AppSuccess) Marshal() []byte {
|
||||
marshal, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return marshal
|
||||
}
|
||||
|
||||
func NewAppSuccess(message, code string, data interface{}) *AppSuccess {
|
||||
return &AppSuccess{
|
||||
Status: true,
|
||||
Message: message,
|
||||
Code: code,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
339
backend/internal/client/users/db/postgresql.go
Executable file
339
backend/internal/client/users/db/postgresql.go
Executable file
@@ -0,0 +1,339 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"bankline/internal/client/users"
|
||||
"bankline/pkg/client/postgresql"
|
||||
"bankline/pkg/logging"
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v4"
|
||||
_ "github.com/lib/pq"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) users.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (r repository) GetNews(ctx context.Context, limit, page int) (users.DataNewsDTO, error) {
|
||||
|
||||
var dt users.DataNewsDTO
|
||||
|
||||
qC := `select count(*) from news;`
|
||||
if err := r.client.QueryRow(ctx, qC).Scan(&dt.Count); err != nil {
|
||||
r.logger.Error("count news :::", err)
|
||||
return dt, err
|
||||
}
|
||||
|
||||
q := ` SELECT
|
||||
n.id, n.title,
|
||||
n.date_release, n.img,
|
||||
nc.en, nc.tm, nc.ru
|
||||
FROM news n
|
||||
LEFT JOIN news_content nc ON n.id = nc.news_id
|
||||
ORDER BY n.date_release DESC `
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if limit == 0 || page == 0 {
|
||||
q += ";"
|
||||
rows, err = r.client.Query(ctx, q)
|
||||
} else {
|
||||
q += "limit $1 offset $2;"
|
||||
rows, err = r.client.Query(ctx, q, limit, (page-1)*limit)
|
||||
}
|
||||
if err != nil {
|
||||
r.logger.Error("get news :::", err)
|
||||
return dt, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
ns := []users.NewsDTO{}
|
||||
for rows.Next() {
|
||||
var n users.NewsDTO
|
||||
errN := rows.Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.DataRelease, &n.Image,
|
||||
&n.Content.En, &n.Content.Tm, &n.Content.Ru,
|
||||
)
|
||||
if errN != nil {
|
||||
r.logger.Error("errN :::", errN)
|
||||
continue
|
||||
}
|
||||
|
||||
ns = append(ns, n)
|
||||
}
|
||||
dt.News = ns
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) GetCategories(ctx context.Context) ([]users.CategoryDTO, error) {
|
||||
|
||||
q := ` SELECT
|
||||
c.id, c.name, c.img,
|
||||
COALESCE(
|
||||
jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'id', sc.id, 'categoryId', sc.category_id,
|
||||
'name', sc.name, 'count', sc.count,
|
||||
'content', jsonb_build_object(
|
||||
'en', COALESCE(scc.en, ''),
|
||||
'ru', COALESCE(scc.ru, ''),
|
||||
'tm', COALESCE(scc.tm, '')
|
||||
)
|
||||
)
|
||||
ORDER BY sc.created_at DESC
|
||||
) FILTER (WHERE sc.id IS NOT NULL AND sc.status = true),
|
||||
'[]'
|
||||
) AS sub_categories
|
||||
FROM categories c
|
||||
LEFT JOIN sub_categories sc ON sc.category_id = c.id
|
||||
LEFT JOIN sub_categories_content scc ON sc.id = scc.sub_category_id
|
||||
WHERE c.status = true
|
||||
GROUP BY c.id
|
||||
ORDER BY c.created_at ASC;`
|
||||
|
||||
rows, err := r.client.Query(ctx, q)
|
||||
if err != nil {
|
||||
r.logger.Error("get categories :::", err)
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
cs := []users.CategoryDTO{}
|
||||
for rows.Next() {
|
||||
var c users.CategoryDTO
|
||||
errC := rows.Scan(
|
||||
&c.Id, &c.Name, &c.Image,
|
||||
&c.SubCategories,
|
||||
)
|
||||
if errC != nil {
|
||||
r.logger.Error("errC :::", errC)
|
||||
continue
|
||||
}
|
||||
|
||||
cs = append(cs, c)
|
||||
}
|
||||
|
||||
return cs, nil
|
||||
}
|
||||
|
||||
func (r repository) GetBanners(ctx context.Context, limit, page int) (users.DataBannerDTO, error) {
|
||||
|
||||
var dt users.DataBannerDTO
|
||||
|
||||
qC := `select count(*) from banner;`
|
||||
if err := r.client.QueryRow(ctx, qC).Scan(&dt.Count); err != nil {
|
||||
r.logger.Error("count banners :::", err)
|
||||
return dt, err
|
||||
}
|
||||
|
||||
q := ` SELECT
|
||||
id, title,
|
||||
content_tm, content_ru, content_en,
|
||||
img, created_at
|
||||
FROM banner
|
||||
ORDER BY created_at DESC `
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if limit == 0 || page == 0 {
|
||||
q += ";"
|
||||
rows, err = r.client.Query(ctx, q)
|
||||
} else {
|
||||
q += "limit $1 offset $2;"
|
||||
rows, err = r.client.Query(ctx, q, limit, (page-1)*limit)
|
||||
}
|
||||
if err != nil {
|
||||
r.logger.Error("get banners :::", err)
|
||||
return dt, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
bs := []users.BannerDTO{}
|
||||
for rows.Next() {
|
||||
var b users.BannerDTO
|
||||
errB := rows.Scan(
|
||||
&b.Id, &b.Title,
|
||||
&b.ContentTm, &b.ContentRu, &b.ContentEn,
|
||||
&b.Image, &b.CreatedAt,
|
||||
)
|
||||
if errB != nil {
|
||||
r.logger.Error("errB :::", errB)
|
||||
continue
|
||||
}
|
||||
|
||||
bs = append(bs, b)
|
||||
}
|
||||
dt.Banners = bs
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) GetStatics(ctx context.Context, limit, page int) (users.DataStaticDTO, error) {
|
||||
|
||||
var dt users.DataStaticDTO
|
||||
|
||||
qC := `select count(*) from static;`
|
||||
if err := r.client.QueryRow(ctx, qC).Scan(&dt.Count); err != nil {
|
||||
r.logger.Error("count statics :::", err)
|
||||
return dt, err
|
||||
}
|
||||
|
||||
q := ` SELECT
|
||||
id, logo, title,
|
||||
content_tm, content_ru, content_en,
|
||||
created_at
|
||||
FROM static
|
||||
ORDER BY created_at DESC `
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if limit == 0 || page == 0 {
|
||||
q += ";"
|
||||
rows, err = r.client.Query(ctx, q)
|
||||
} else {
|
||||
q += "limit $1 offset $2;"
|
||||
rows, err = r.client.Query(ctx, q, limit, (page-1)*limit)
|
||||
}
|
||||
if err != nil {
|
||||
r.logger.Error("get statics :::", err)
|
||||
return dt, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
ss := []users.StaticDTO{}
|
||||
for rows.Next() {
|
||||
var s users.StaticDTO
|
||||
errS := rows.Scan(
|
||||
&s.Id, &s.Logo, &s.Title,
|
||||
&s.ContentTm, &s.ContentRu, &s.ContentEn,
|
||||
&s.CreatedAt,
|
||||
)
|
||||
if errS != nil {
|
||||
r.logger.Error("errS :::", errS)
|
||||
continue
|
||||
}
|
||||
|
||||
ss = append(ss, s)
|
||||
}
|
||||
dt.Statics = ss
|
||||
return dt, nil
|
||||
}
|
||||
|
||||
func (r repository) GetStaticById(ctx context.Context, id int) (users.StaticDTO, error) {
|
||||
var s users.StaticDTO
|
||||
|
||||
q := ` SELECT
|
||||
id, logo, title,
|
||||
content_tm, content_ru, content_en,
|
||||
created_at
|
||||
FROM static
|
||||
WHERE id = $1;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, id).Scan(
|
||||
&s.Id, &s.Logo, &s.Title,
|
||||
&s.ContentTm, &s.ContentRu, &s.ContentEn,
|
||||
&s.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (r repository) GetCurrency(ctx context.Context) (users.CurrencyDTO, error) {
|
||||
var cu users.CurrencyDTO
|
||||
|
||||
q := ` SELECT
|
||||
id, title,
|
||||
content_tm, content_ru, content_en,
|
||||
path, created_at
|
||||
FROM currency
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q).Scan(
|
||||
&cu.Id, &cu.Title,
|
||||
&cu.Content.Tm, &cu.Content.Ru, &cu.Content.En,
|
||||
&cu.Path, &cu.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return cu, err
|
||||
}
|
||||
return cu, nil
|
||||
}
|
||||
|
||||
func (r repository) GetSetting(ctx context.Context) (users.SettingDTO, error) {
|
||||
var s users.SettingDTO
|
||||
|
||||
q := ` SELECT
|
||||
uuid::text, logo_r, phone_number, fax_number, help_number, created_at
|
||||
FROM setting
|
||||
ORDER BY id ASC
|
||||
LIMIT 1;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q).Scan(
|
||||
&s.UUID, &s.LogoR, &s.PhoneNumber, &s.FaxNumber, &s.HelpNumber, &s.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (r repository) GetSubCategoryById(ctx context.Context, id int) (users.SubCategoryDTO, error) {
|
||||
var sc users.SubCategoryDTO
|
||||
|
||||
q := ` SELECT
|
||||
sc.id, sc.category_id,
|
||||
sc.name, sc.count,
|
||||
COALESCE(scc.en, ''), COALESCE(scc.tm, ''), COALESCE(scc.ru, '')
|
||||
FROM sub_categories sc
|
||||
LEFT JOIN sub_categories_content scc ON sc.id = scc.sub_category_id
|
||||
WHERE sc.id = $1 AND sc.status = true;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, id).Scan(
|
||||
&sc.Id, &sc.CategoryId,
|
||||
&sc.Name, &sc.Count,
|
||||
&sc.Content.En, &sc.Content.Tm, &sc.Content.Ru,
|
||||
)
|
||||
if err != nil {
|
||||
return sc, err
|
||||
}
|
||||
return sc, nil
|
||||
}
|
||||
|
||||
func (r repository) GetNewsById(ctx context.Context, id int) (users.NewsDTO, error) {
|
||||
var n users.NewsDTO
|
||||
|
||||
q := ` SELECT
|
||||
n.id, n.title,
|
||||
n.date_release, n.img,
|
||||
nc.en, nc.tm, nc.ru
|
||||
FROM news n
|
||||
LEFT JOIN news_content nc ON n.id = nc.news_id
|
||||
WHERE n.id = $1;`
|
||||
|
||||
err := r.client.QueryRow(ctx, q, id).Scan(
|
||||
&n.Id, &n.Title,
|
||||
&n.DataRelease, &n.Image,
|
||||
&n.Content.En, &n.Content.Tm, &n.Content.Ru,
|
||||
)
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
84
backend/internal/client/users/dto.go
Executable file
84
backend/internal/client/users/dto.go
Executable file
@@ -0,0 +1,84 @@
|
||||
package users
|
||||
|
||||
import "time"
|
||||
|
||||
type DataNewsDTO struct {
|
||||
News []NewsDTO `json:"news"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type NewsDTO struct {
|
||||
Id int `json:"id"`
|
||||
Title Language `json:"title"`
|
||||
Content Language `json:"content"`
|
||||
Image string `json:"imagePath"`
|
||||
DataRelease time.Time `json:"dateRelease"`
|
||||
}
|
||||
|
||||
type Language struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
|
||||
type CategoryDTO struct {
|
||||
Id int `json:"id"`
|
||||
Name Language `json:"name"`
|
||||
Image string `json:"imagePath"`
|
||||
SubCategories []SubCategoryDTO `json:"subCategories"`
|
||||
}
|
||||
|
||||
type SubCategoryDTO struct {
|
||||
Id int `json:"id"`
|
||||
CategoryId int `json:"categoryId"`
|
||||
Name Language `json:"name"`
|
||||
Content Language `json:"content"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type DataBannerDTO struct {
|
||||
Banners []BannerDTO `json:"banners"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type BannerDTO struct {
|
||||
Id int `json:"id"`
|
||||
Title Language `json:"title"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
Image string `json:"imagePath"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type DataStaticDTO struct {
|
||||
Statics []StaticDTO `json:"statics"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type StaticDTO struct {
|
||||
Id int `json:"id"`
|
||||
Logo string `json:"logo"`
|
||||
Title Language `json:"title"`
|
||||
ContentTm string `json:"contentTm"`
|
||||
ContentRu string `json:"contentRu"`
|
||||
ContentEn string `json:"contentEn"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type CurrencyDTO struct {
|
||||
Id int `json:"id"`
|
||||
Title Language `json:"title"`
|
||||
Content Language `json:"content"`
|
||||
Path string `json:"path"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
type SettingDTO struct {
|
||||
UUID string `json:"UUID"`
|
||||
LogoR string `json:"logoR"`
|
||||
PhoneNumber string `json:"phoneNumber"`
|
||||
FaxNumber string `json:"faxNumber"`
|
||||
HelpNumber string `json:"helpNumber"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
265
backend/internal/client/users/handler.go
Executable file
265
backend/internal/client/users/handler.go
Executable file
@@ -0,0 +1,265 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/handlers"
|
||||
"bankline/pkg/logging"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
getNewsURL = "/news"
|
||||
getOneNewsURL = "/news/:id"
|
||||
getCategoriesURL = "/categories"
|
||||
getOneSubCategoryURL = "/sub-categories/:id"
|
||||
getBannersURL = "/banners"
|
||||
getStaticsURL = "/static"
|
||||
getOneStaticURL = "/static/:id"
|
||||
getCurrencyURL = "/currency"
|
||||
getSettingURL = "/setting"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
|
||||
return &handler{
|
||||
logger: logger,
|
||||
repository: repository,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
router.GET(getNewsURL, h.GetNews)
|
||||
router.GET(getOneNewsURL, h.GetOneNews)
|
||||
router.GET(getCategoriesURL, h.GetCategories)
|
||||
router.GET(getOneSubCategoryURL, h.GetSubCategory)
|
||||
router.GET(getBannersURL, h.GetBanners)
|
||||
router.GET(getStaticsURL, h.GetStatics)
|
||||
router.GET(getOneStaticURL, h.GetOneStatic)
|
||||
router.GET(getCurrencyURL, h.GetCurrency)
|
||||
router.GET(getSettingURL, h.GetSetting)
|
||||
}
|
||||
|
||||
// =================================================================================
|
||||
|
||||
// GetNews godoc
|
||||
// @Description all news
|
||||
// @Tags news
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param limit query int false "limit"
|
||||
// @Param page query int false "page"
|
||||
// @Success 200 {object} DataNewsDTO
|
||||
// @Router /client/users/news [get]
|
||||
func (h *handler) GetNews(c *gin.Context) {
|
||||
limitS, _ := c.GetQuery("limit")
|
||||
pageS, _ := c.GetQuery("page")
|
||||
|
||||
limit, _ := strconv.Atoi(limitS)
|
||||
page, _ := strconv.Atoi(pageS)
|
||||
|
||||
result, err := h.repository.GetNews(c.Request.Context(), limit, page)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// GetOneNews godoc
|
||||
// @Description news by id
|
||||
// @Tags news
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path int true "news ID"
|
||||
// @Success 200 {object} NewsDTO
|
||||
// @Router /client/users/news/{id} [get]
|
||||
func (h *handler) GetOneNews(c *gin.Context) {
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.GetNewsById(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// GetSubCategory godoc
|
||||
// @Description sub-category by id
|
||||
// @Tags categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path int true "sub-category ID"
|
||||
// @Success 200 {object} SubCategoryDTO
|
||||
// @Router /client/users/sub-categories/{id} [get]
|
||||
func (h *handler) GetSubCategory(c *gin.Context) {
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.GetSubCategoryById(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// GetBanners godoc
|
||||
// @Description all banners
|
||||
// @Tags banners
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param limit query int false "limit"
|
||||
// @Param page query int false "page"
|
||||
// @Success 200 {object} DataBannerDTO
|
||||
// @Router /client/users/banners [get]
|
||||
func (h *handler) GetBanners(c *gin.Context) {
|
||||
limitS, _ := c.GetQuery("limit")
|
||||
pageS, _ := c.GetQuery("page")
|
||||
|
||||
limit, _ := strconv.Atoi(limitS)
|
||||
page, _ := strconv.Atoi(pageS)
|
||||
|
||||
result, err := h.repository.GetBanners(c.Request.Context(), limit, page)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// GetStatics godoc
|
||||
// @Description all static data
|
||||
// @Tags statics
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param limit query int false "limit"
|
||||
// @Param page query int false "page"
|
||||
// @Success 200 {object} DataStaticDTO
|
||||
// @Router /client/users/static [get]
|
||||
func (h *handler) GetStatics(c *gin.Context) {
|
||||
limitS, _ := c.GetQuery("limit")
|
||||
pageS, _ := c.GetQuery("page")
|
||||
|
||||
limit, _ := strconv.Atoi(limitS)
|
||||
page, _ := strconv.Atoi(pageS)
|
||||
|
||||
result, err := h.repository.GetStatics(c.Request.Context(), limit, page)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// GetOneStatic godoc
|
||||
// @Description static data by id
|
||||
// @Tags statics
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path int true "static ID"
|
||||
// @Success 200 {object} StaticDTO
|
||||
// @Router /client/users/static/{id} [get]
|
||||
func (h *handler) GetOneStatic(c *gin.Context) {
|
||||
id, err := strconv.Atoi(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotAcceptable)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.repository.GetStaticById(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// GetCurrency godoc
|
||||
// @Description latest currency content (title + HTML table per language)
|
||||
// @Tags currency
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} CurrencyDTO
|
||||
// @Router /client/users/currency [get]
|
||||
func (h *handler) GetCurrency(c *gin.Context) {
|
||||
result, err := h.repository.GetCurrency(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// GetSetting godoc
|
||||
// @Description site setting (logo and contact numbers)
|
||||
// @Tags settings
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} SettingDTO
|
||||
// @Router /client/users/setting [get]
|
||||
func (h *handler) GetSetting(c *gin.Context) {
|
||||
result, err := h.repository.GetSetting(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
|
||||
// GetCategories godoc
|
||||
// @Description all active categories with their active subcategories
|
||||
// @Tags categories
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {array} CategoryDTO
|
||||
// @Router /client/users/categories [get]
|
||||
func (h *handler) GetCategories(c *gin.Context) {
|
||||
result, err := h.repository.GetCategories(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
successResult := appresult.Success
|
||||
successResult.Data = result
|
||||
c.JSON(http.StatusOK, successResult)
|
||||
}
|
||||
19
backend/internal/client/users/storage.go
Executable file
19
backend/internal/client/users/storage.go
Executable file
@@ -0,0 +1,19 @@
|
||||
package users
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
GetNews(ctx context.Context, limit, page int) (DataNewsDTO, error)
|
||||
GetNewsById(ctx context.Context, id int) (NewsDTO, error)
|
||||
|
||||
GetCategories(ctx context.Context) ([]CategoryDTO, error)
|
||||
GetSubCategoryById(ctx context.Context, id int) (SubCategoryDTO, error)
|
||||
|
||||
GetBanners(ctx context.Context, limit, page int) (DataBannerDTO, error)
|
||||
|
||||
GetStatics(ctx context.Context, limit, page int) (DataStaticDTO, error)
|
||||
GetStaticById(ctx context.Context, id int) (StaticDTO, error)
|
||||
|
||||
GetCurrency(ctx context.Context) (CurrencyDTO, error)
|
||||
GetSetting(ctx context.Context) (SettingDTO, error)
|
||||
}
|
||||
49
backend/internal/config/config.go
Executable file
49
backend/internal/config/config.go
Executable file
@@ -0,0 +1,49 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"bankline/pkg/logging"
|
||||
"sync"
|
||||
|
||||
"github.com/ilyakaznacheev/cleanenv"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
IsDebug *bool `yaml:"is_debug" env-required:"true"`
|
||||
Listen struct {
|
||||
Type string `yaml:"type" env-default:"port"`
|
||||
BindIP string `yaml:"bind_ip" env-default:"0.0.0.0"`
|
||||
Port string `yaml:"port" env-default:"8080"`
|
||||
} `yaml:"listen"`
|
||||
PublicFilePath string `yaml:"public_file_path" env-required:"true"`
|
||||
Storage StorageConfig `yaml:"storage"`
|
||||
JwtKey string `yaml:"jwt_key" env-required:"true"`
|
||||
AppVersion string `yaml:"app_version" env-required:"true"`
|
||||
}
|
||||
|
||||
type StorageConfig struct {
|
||||
PgPoolMaxConn int `yaml:"pg_pool_max_conn" env-required:"true"`
|
||||
Host string `json:"host"`
|
||||
Port string `json:"port"`
|
||||
Database string `json:"database"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
var instance *Config
|
||||
var once sync.Once
|
||||
|
||||
func GetConfig() *Config {
|
||||
once.Do(func() {
|
||||
|
||||
pathConfig := "./config.yaml"
|
||||
logger := logging.GetLogger()
|
||||
logger.Info("read application configuration")
|
||||
instance = &Config{}
|
||||
if err := cleanenv.ReadConfig(pathConfig, instance); err != nil {
|
||||
help, _ := cleanenv.GetDescription(instance, nil)
|
||||
logger.Info(help)
|
||||
logger.Fatal(err)
|
||||
}
|
||||
})
|
||||
return instance
|
||||
}
|
||||
9
backend/internal/handlers/handler.go
Executable file
9
backend/internal/handlers/handler.go
Executable file
@@ -0,0 +1,9 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Handler interface {
|
||||
Register(router *gin.RouterGroup)
|
||||
}
|
||||
119
backend/internal/handlers/manager/manager.go
Executable file
119
backend/internal/handlers/manager/manager.go
Executable file
@@ -0,0 +1,119 @@
|
||||
package handlermanager
|
||||
|
||||
import (
|
||||
"bankline/internal/admin/auth"
|
||||
authdb "bankline/internal/admin/auth/db"
|
||||
"bankline/internal/admin/banner"
|
||||
bannerdb "bankline/internal/admin/banner/db"
|
||||
"bankline/internal/admin/category"
|
||||
catdb "bankline/internal/admin/category/db"
|
||||
"bankline/internal/admin/currency"
|
||||
currencydb "bankline/internal/admin/currency/db"
|
||||
"bankline/internal/admin/news"
|
||||
newsdb "bankline/internal/admin/news/db"
|
||||
"bankline/internal/admin/setting"
|
||||
settingdb "bankline/internal/admin/setting/db"
|
||||
"bankline/internal/admin/static"
|
||||
staticdb "bankline/internal/admin/static/db"
|
||||
"bankline/internal/admin/sub_category"
|
||||
subcategorydb "bankline/internal/admin/sub_category/db"
|
||||
adminui "bankline/internal/admin/ui"
|
||||
"bankline/internal/appresult"
|
||||
"bankline/internal/client/users"
|
||||
usersdb "bankline/internal/client/users/db"
|
||||
"bankline/pkg/logging"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-gonic/gin"
|
||||
_ "github.com/swaggo/swag"
|
||||
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
const (
|
||||
authURL = "/v1/admin"
|
||||
|
||||
categoryURL = "/v1/admin/categories"
|
||||
subCategoryURL = "/v1/admin/sub-categories"
|
||||
settingURL = "/v1/admin/setting"
|
||||
bannerURL = "/v1/admin/banner"
|
||||
newsURL = "/v1/admin/news"
|
||||
staticURL = "/v1/admin/static"
|
||||
currencyURL = "/v1/admin/currency"
|
||||
|
||||
usersURL = "/v1/client/users"
|
||||
)
|
||||
|
||||
func Manager(client *pgxpool.Pool, logger *logging.Logger) *gin.Engine {
|
||||
|
||||
router := gin.Default()
|
||||
|
||||
router.Use(cors.New(cors.Config{
|
||||
AllowOrigins: []string{"*"},
|
||||
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", http.MethodGet, http.MethodPatch, http.MethodPost},
|
||||
AllowHeaders: []string{
|
||||
"Content-Type", "Content-Length", "Accept-Encoding",
|
||||
"Authorization", "Cache-Control",
|
||||
"access-control-allow-origin", "access-control-allow-headers",
|
||||
},
|
||||
ExposeHeaders: []string{"Content-Length"},
|
||||
AllowCredentials: true,
|
||||
}))
|
||||
|
||||
authRouterManager := router.Group(authURL)
|
||||
authRepository := authdb.NewRepository(client, logger)
|
||||
authRouterHandler := auth.NewHandler(logger, authRepository)
|
||||
authRouterHandler.Register(authRouterManager)
|
||||
|
||||
categoryRouterManager := router.Group(categoryURL)
|
||||
categoryRouterManager.Use(appresult.JwtTokenCheck())
|
||||
categoryRepository := catdb.NewRepository(client, logger)
|
||||
categoryRouterHandler := category.NewHandler(categoryRepository, logger)
|
||||
categoryRouterHandler.Register(categoryRouterManager)
|
||||
|
||||
subCategoryRouterManager := router.Group(subCategoryURL)
|
||||
subCategoryRouterManager.Use(appresult.JwtTokenCheck())
|
||||
subCategoryRepository := subcategorydb.NewRepository(client, logger)
|
||||
subCategoryRouterHandler := sub_category.NewHandler(subCategoryRepository, logger)
|
||||
subCategoryRouterHandler.Register(subCategoryRouterManager)
|
||||
|
||||
settingRouterManager := router.Group(settingURL)
|
||||
settingRouterManager.Use(appresult.JwtTokenCheck())
|
||||
settingRepository := settingdb.NewRepository(client, logger)
|
||||
settingRouterHandler := setting.NewHandler(settingRepository, logger)
|
||||
settingRouterHandler.Register(settingRouterManager)
|
||||
|
||||
bannerRouterManager := router.Group(bannerURL)
|
||||
bannerRouterManager.Use(appresult.JwtTokenCheck())
|
||||
bannerRepository := bannerdb.NewRepository(client, logger)
|
||||
bannerRouterHandler := banner.NewHandler(bannerRepository, logger)
|
||||
bannerRouterHandler.Register(bannerRouterManager)
|
||||
|
||||
newsRouterManager := router.Group(newsURL)
|
||||
newsRouterManager.Use(appresult.JwtTokenCheck())
|
||||
newsRepository := newsdb.NewRepository(client, logger)
|
||||
newsRouterHandler := news.NewHandler(newsRepository, logger)
|
||||
newsRouterHandler.Register(newsRouterManager)
|
||||
|
||||
staticRouterManager := router.Group(staticURL)
|
||||
staticRouterManager.Use(appresult.JwtTokenCheck())
|
||||
staticRepository := staticdb.NewRepository(client, logger)
|
||||
staticRouterHandler := static.NewHandler(staticRepository, logger)
|
||||
staticRouterHandler.Register(staticRouterManager)
|
||||
|
||||
currencyRouterManager := router.Group(currencyURL)
|
||||
currencyRouterManager.Use(appresult.JwtTokenCheck())
|
||||
currencyRepository := currencydb.NewRepository(client, logger)
|
||||
currencyRouterHandler := currency.NewHandler(currencyRepository, logger)
|
||||
currencyRouterHandler.Register(currencyRouterManager)
|
||||
|
||||
usersRouterManager := router.Group(usersURL)
|
||||
usersRepository := usersdb.NewRepository(client, logger)
|
||||
usersRouterHandler := users.NewHandler(logger, usersRepository)
|
||||
usersRouterHandler.Register(usersRouterManager)
|
||||
|
||||
adminui.Register(router)
|
||||
|
||||
return router
|
||||
}
|
||||
58
backend/internal/listing/listing.go
Normal file
58
backend/internal/listing/listing.go
Normal file
@@ -0,0 +1,58 @@
|
||||
// Package listing provides common query parameters for admin list endpoints:
|
||||
// pagination, search and sorting.
|
||||
package listing
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Params holds common list query options.
|
||||
type Params struct {
|
||||
Limit int
|
||||
Page int
|
||||
Search string
|
||||
Sort string
|
||||
Order string
|
||||
}
|
||||
|
||||
// FromQuery extracts list params from the request query string.
|
||||
func FromQuery(c *gin.Context) Params {
|
||||
limit, _ := strconv.Atoi(c.Query("limit"))
|
||||
page, _ := strconv.Atoi(c.Query("page"))
|
||||
return Params{
|
||||
Limit: limit,
|
||||
Page: page,
|
||||
Search: strings.TrimSpace(c.Query("search")),
|
||||
Sort: c.Query("sort"),
|
||||
Order: strings.ToLower(c.Query("order")),
|
||||
}
|
||||
}
|
||||
|
||||
// Paginated reports whether pagination should be applied.
|
||||
// Mirrors the pre-existing behaviour: limit=0 or page=0 returns all rows.
|
||||
func (p Params) Paginated() bool { return p.Limit > 0 && p.Page > 0 }
|
||||
|
||||
// Offset returns the SQL offset for the current page.
|
||||
func (p Params) Offset() int { return (p.Page - 1) * p.Limit }
|
||||
|
||||
// SearchPattern returns an ILIKE pattern for the search term.
|
||||
func (p Params) SearchPattern() string { return "%" + p.Search + "%" }
|
||||
|
||||
// OrderClause returns a safe ORDER BY clause. The requested sort key is looked
|
||||
// up in the whitelist map (query key -> SQL column); unknown or empty keys fall
|
||||
// back to the def expression. User input is never interpolated directly.
|
||||
func (p Params) OrderClause(whitelist map[string]string, def string) string {
|
||||
col, ok := whitelist[p.Sort]
|
||||
if !ok {
|
||||
return " ORDER BY " + def + " "
|
||||
}
|
||||
dir := "DESC"
|
||||
if p.Order == "asc" {
|
||||
dir = "ASC"
|
||||
}
|
||||
return fmt.Sprintf(" ORDER BY %s %s ", col, dir)
|
||||
}
|
||||
0
backend/logs/all.log
Executable file
0
backend/logs/all.log
Executable file
6
backend/package.json
Executable file
6
backend/package.json
Executable file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"apps" : [{
|
||||
"name" : "bankline",
|
||||
"script" : "./app"
|
||||
}]
|
||||
}
|
||||
BIN
backend/pkg/.DS_Store
vendored
Normal file
BIN
backend/pkg/.DS_Store
vendored
Normal file
Binary file not shown.
BIN
backend/pkg/client/.DS_Store
vendored
Executable file
BIN
backend/pkg/client/.DS_Store
vendored
Executable file
Binary file not shown.
63
backend/pkg/client/postgresql/postgresql.go
Executable file
63
backend/pkg/client/postgresql/postgresql.go
Executable file
@@ -0,0 +1,63 @@
|
||||
package postgresql
|
||||
|
||||
import (
|
||||
"bankline/internal/config"
|
||||
repeatable "bankline/pkg/utils"
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgconn"
|
||||
"github.com/jackc/pgx/v4"
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
type Client interface {
|
||||
Exec(ctx context.Context, sql string, arguments ...interface{}) (pgconn.CommandTag, error)
|
||||
Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error)
|
||||
QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row
|
||||
Begin(ctx context.Context) (pgx.Tx, error)
|
||||
}
|
||||
|
||||
func NewClient(ctx context.Context, maxAttempts int, sc config.StorageConfig) (*pgxpool.Pool, error) {
|
||||
dsn := fmt.Sprintf(
|
||||
"postgresql://%s:%s@%s:%s/%s",
|
||||
url.QueryEscape(sc.Username),
|
||||
url.QueryEscape(sc.Password),
|
||||
sc.Host, sc.Port, sc.Database,
|
||||
)
|
||||
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse pg config: %w", err)
|
||||
}
|
||||
|
||||
cfg.MaxConns = int32(sc.PgPoolMaxConn)
|
||||
cfg.HealthCheckPeriod = 2 * time.Second
|
||||
cfg.MaxConnLifetime = 24 * time.Hour
|
||||
cfg.MaxConnIdleTime = 2 * time.Second
|
||||
|
||||
cfg.ConnConfig.ConnectTimeout = 1 * time.Second
|
||||
cfg.ConnConfig.DialFunc = (&net.Dialer{
|
||||
KeepAlive: cfg.HealthCheckPeriod,
|
||||
Timeout: cfg.ConnConfig.ConnectTimeout,
|
||||
}).DialContext
|
||||
|
||||
var pool *pgxpool.Pool
|
||||
err = repeatable.DoWithTries(func() error {
|
||||
p, err := pgxpool.ConnectConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pool = p
|
||||
return nil
|
||||
}, maxAttempts, 5*time.Second)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error connecting to postgresql after retries: %w", err)
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
87
backend/pkg/logging/logging.go
Executable file
87
backend/pkg/logging/logging.go
Executable file
@@ -0,0 +1,87 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"runtime"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type writerHook struct {
|
||||
Writer []io.Writer
|
||||
LogLevels []logrus.Level
|
||||
}
|
||||
|
||||
const (
|
||||
pathLog = "./logs/all.log"
|
||||
)
|
||||
|
||||
func (hook *writerHook) Fire(entry *logrus.Entry) error {
|
||||
line, err := entry.String()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, w := range hook.Writer {
|
||||
_, err := w.Write([]byte(line))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (hook *writerHook) Levels() []logrus.Level {
|
||||
return hook.LogLevels
|
||||
}
|
||||
|
||||
var e *logrus.Entry
|
||||
|
||||
type Logger struct {
|
||||
*logrus.Entry
|
||||
}
|
||||
|
||||
func GetLogger() *Logger {
|
||||
return &Logger{e}
|
||||
}
|
||||
|
||||
func (l *Logger) GetLoggerWithField(k string, v interface{}) *Logger {
|
||||
return &Logger{l.WithField(k, v)}
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
l := logrus.New()
|
||||
l.SetReportCaller(true)
|
||||
l.Formatter = &logrus.TextFormatter{
|
||||
CallerPrettyfier: func(frame *runtime.Frame) (function string, file string) {
|
||||
filename := path.Base(frame.File)
|
||||
return fmt.Sprintf("%s()", frame.Function), fmt.Sprintf("%s:%d", filename, frame.Line)
|
||||
},
|
||||
DisableColors: false,
|
||||
FullTimestamp: true,
|
||||
}
|
||||
|
||||
err := os.MkdirAll("logs", 0755)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
allFile, err := os.OpenFile(pathLog, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0640)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
l.SetOutput(io.Discard)
|
||||
|
||||
l.AddHook(&writerHook{
|
||||
Writer: []io.Writer{allFile, os.Stdout},
|
||||
LogLevels: logrus.AllLevels,
|
||||
})
|
||||
|
||||
l.SetLevel(logrus.TraceLevel)
|
||||
|
||||
e = logrus.NewEntry(l)
|
||||
}
|
||||
49
backend/pkg/minio/minio.go
Normal file
49
backend/pkg/minio/minio.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package minio
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
// Must match deployment/Dockerfile.minio MINIO_ROOT_USER / MINIO_ROOT_PASSWORD.
|
||||
const (
|
||||
BucketName = "dev-minio"
|
||||
endpoint = "main-minio:9000"
|
||||
accessKeyID = "MINIO_ROOT_USER"
|
||||
secretAccessKey = "MINIO_ROOT_PASSWORD"
|
||||
)
|
||||
|
||||
func ConnectionMinio() (*minio.Client, error) {
|
||||
minioClient, errInit := minio.New(endpoint, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
|
||||
Secure: false,
|
||||
})
|
||||
if errInit != nil {
|
||||
fmt.Println("minio connection:", errInit)
|
||||
return nil, errInit
|
||||
}
|
||||
return minioClient, nil
|
||||
}
|
||||
|
||||
// EnsureBucket creates the app bucket when it does not exist yet.
|
||||
func EnsureBucket(ctx context.Context, client *minio.Client) error {
|
||||
exists, err := client.BucketExists(ctx, BucketName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("bucket exists check: %w", err)
|
||||
}
|
||||
if exists {
|
||||
return nil
|
||||
}
|
||||
if err := client.MakeBucket(ctx, BucketName, minio.MakeBucketOptions{}); err != nil {
|
||||
// Another request may have created it concurrently.
|
||||
exists, checkErr := client.BucketExists(ctx, BucketName)
|
||||
if checkErr == nil && exists {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("make bucket: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
89
backend/pkg/utils/utils.go
Executable file
89
backend/pkg/utils/utils.go
Executable file
@@ -0,0 +1,89 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bankline/internal/config"
|
||||
"fmt"
|
||||
"mime/multipart"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt"
|
||||
)
|
||||
|
||||
const (
|
||||
SecretKey = "8a96a17e136bee4e61b3f9c443a4a408bfb452df763ed42d9db2f285aaa43a5c+"
|
||||
)
|
||||
|
||||
func DoWithTries(fn func() error, attemtps int, delay time.Duration) (err error) {
|
||||
for attemtps > 0 {
|
||||
if err = fn(); err != nil {
|
||||
time.Sleep(delay)
|
||||
attemtps--
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func CreateFile(folderName string, file *multipart.FileHeader, r *gin.Context) (string, error) {
|
||||
cfg := config.GetConfig()
|
||||
appName := fmt.Sprintf("%d%s", time.Now().UnixNano(), filepath.Ext(filepath.Base(file.Filename)))
|
||||
appDirPath := cfg.PublicFilePath + "/" + folderName
|
||||
|
||||
err := os.MkdirAll(appDirPath, os.ModePerm)
|
||||
if err != nil {
|
||||
return "str", err
|
||||
}
|
||||
|
||||
pathApp := fmt.Sprintf("%s/%s", appDirPath, appName)
|
||||
if err := r.SaveUploadedFile(file, pathApp); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
pathApp = "/public/" + folderName + "/" + appName
|
||||
return pathApp, err
|
||||
}
|
||||
|
||||
func RemoveFile(path string) error {
|
||||
err := os.RemoveAll(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GenerateTokenPair(id int) (map[string]string, error) {
|
||||
cfg := config.GetConfig()
|
||||
token := jwt.New(jwt.SigningMethodHS256)
|
||||
|
||||
claims := token.Claims.(jwt.MapClaims)
|
||||
claims["id"] = id
|
||||
claims["admin"] = true
|
||||
claims["exp"] = time.Now().Add(time.Minute * 60).Unix()
|
||||
|
||||
t, err := token.SignedString([]byte(cfg.JwtKey))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
refreshToken := jwt.New(jwt.SigningMethodHS256)
|
||||
rtClaims := refreshToken.Claims.(jwt.MapClaims)
|
||||
rtClaims["id"] = id
|
||||
rtClaims["exp"] = time.Now().Add(time.Hour * 24 * 30).Unix()
|
||||
|
||||
rt, err := refreshToken.SignedString([]byte(SecretKey))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return map[string]string{
|
||||
"accessToken": t,
|
||||
"refreshToken": rt,
|
||||
}, nil
|
||||
}
|
||||
23
backend/scripts/deploy.sh
Executable file
23
backend/scripts/deploy.sh
Executable file
@@ -0,0 +1,23 @@
|
||||
#!/bin/sh
|
||||
# Build, push to the self-hosted registry, and trigger Watchtower.
|
||||
#
|
||||
# Run this ON THE VPS (registry is bound to 127.0.0.1, so it's only
|
||||
# reachable locally). To run it from your laptop instead, first open a
|
||||
# tunnel: ssh -L 5000:localhost:5000 -L 8080:localhost:8080 user@vps
|
||||
set -e
|
||||
|
||||
IMAGE=localhost:5000/bankline:latest
|
||||
WATCHTOWER_URL=http://localhost:8080/v1/update
|
||||
|
||||
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
|
||||
docker build -t "$IMAGE" -f "$SCRIPT_DIR/Dockerfile" "$SCRIPT_DIR"
|
||||
docker push "$IMAGE"
|
||||
|
||||
if [ -z "$WATCHTOWER_TOKEN" ]; then
|
||||
echo "WATCHTOWER_TOKEN not set — skipping trigger; Watchtower will pick it up on its next poll." >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
curl -sf -H "Authorization: Bearer $WATCHTOWER_TOKEN" "$WATCHTOWER_URL"
|
||||
echo "Watchtower update triggered."
|
||||
2
backend/vendor/github.com/BurntSushi/toml/.gitignore
generated
vendored
Normal file
2
backend/vendor/github.com/BurntSushi/toml/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/toml.test
|
||||
/toml-test
|
||||
21
backend/vendor/github.com/BurntSushi/toml/COPYING
generated
vendored
Normal file
21
backend/vendor/github.com/BurntSushi/toml/COPYING
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2013 TOML authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
120
backend/vendor/github.com/BurntSushi/toml/README.md
generated
vendored
Normal file
120
backend/vendor/github.com/BurntSushi/toml/README.md
generated
vendored
Normal file
@@ -0,0 +1,120 @@
|
||||
TOML stands for Tom's Obvious, Minimal Language. This Go package provides a
|
||||
reflection interface similar to Go's standard library `json` and `xml` packages.
|
||||
|
||||
Compatible with TOML version [v1.1.0](https://toml.io/en/v1.1.0).
|
||||
|
||||
Documentation: https://pkg.go.dev/github.com/BurntSushi/toml
|
||||
|
||||
See the [releases page](https://github.com/BurntSushi/toml/releases) for a
|
||||
changelog; this information is also in the git tag annotations (e.g. `git show
|
||||
v0.4.0`).
|
||||
|
||||
This library requires Go 1.18 or newer; add it to your go.mod with:
|
||||
|
||||
% go get github.com/BurntSushi/toml@latest
|
||||
|
||||
It also comes with a TOML validator CLI tool:
|
||||
|
||||
% go install github.com/BurntSushi/toml/cmd/tomlv@latest
|
||||
% tomlv some-toml-file.toml
|
||||
|
||||
### Examples
|
||||
For the simplest example, consider some TOML file as just a list of keys and
|
||||
values:
|
||||
|
||||
```toml
|
||||
Age = 25
|
||||
Cats = [ "Cauchy", "Plato" ]
|
||||
Pi = 3.14
|
||||
Perfection = [ 6, 28, 496, 8128 ]
|
||||
DOB = 1987-07-05T05:45:00Z
|
||||
```
|
||||
|
||||
Which can be decoded with:
|
||||
|
||||
```go
|
||||
type Config struct {
|
||||
Age int
|
||||
Cats []string
|
||||
Pi float64
|
||||
Perfection []int
|
||||
DOB time.Time
|
||||
}
|
||||
|
||||
var conf Config
|
||||
_, err := toml.Decode(tomlData, &conf)
|
||||
```
|
||||
|
||||
You can also use struct tags if your struct field name doesn't map to a TOML key
|
||||
value directly:
|
||||
|
||||
```toml
|
||||
some_key_NAME = "wat"
|
||||
```
|
||||
|
||||
```go
|
||||
type TOML struct {
|
||||
ObscureKey string `toml:"some_key_NAME"`
|
||||
}
|
||||
```
|
||||
|
||||
Beware that like other decoders **only exported fields** are considered when
|
||||
encoding and decoding; private fields are silently ignored.
|
||||
|
||||
### Using the `Marshaler` and `encoding.TextUnmarshaler` interfaces
|
||||
Here's an example that automatically parses values in a `mail.Address`:
|
||||
|
||||
```toml
|
||||
contacts = [
|
||||
"Donald Duck <donald@duckburg.com>",
|
||||
"Scrooge McDuck <scrooge@duckburg.com>",
|
||||
]
|
||||
```
|
||||
|
||||
Can be decoded with:
|
||||
|
||||
```go
|
||||
// Create address type which satisfies the encoding.TextUnmarshaler interface.
|
||||
type address struct {
|
||||
*mail.Address
|
||||
}
|
||||
|
||||
func (a *address) UnmarshalText(text []byte) error {
|
||||
var err error
|
||||
a.Address, err = mail.ParseAddress(string(text))
|
||||
return err
|
||||
}
|
||||
|
||||
// Decode it.
|
||||
func decode() {
|
||||
blob := `
|
||||
contacts = [
|
||||
"Donald Duck <donald@duckburg.com>",
|
||||
"Scrooge McDuck <scrooge@duckburg.com>",
|
||||
]
|
||||
`
|
||||
|
||||
var contacts struct {
|
||||
Contacts []address
|
||||
}
|
||||
|
||||
_, err := toml.Decode(blob, &contacts)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
for _, c := range contacts.Contacts {
|
||||
fmt.Printf("%#v\n", c.Address)
|
||||
}
|
||||
|
||||
// Output:
|
||||
// &mail.Address{Name:"Donald Duck", Address:"donald@duckburg.com"}
|
||||
// &mail.Address{Name:"Scrooge McDuck", Address:"scrooge@duckburg.com"}
|
||||
}
|
||||
```
|
||||
|
||||
To target TOML specifically you can implement `UnmarshalTOML` TOML interface in
|
||||
a similar way.
|
||||
|
||||
### More complex usage
|
||||
See the [`_example/`](/_example) directory for a more complex example.
|
||||
645
backend/vendor/github.com/BurntSushi/toml/decode.go
generated
vendored
Normal file
645
backend/vendor/github.com/BurntSushi/toml/decode.go
generated
vendored
Normal file
@@ -0,0 +1,645 @@
|
||||
package toml
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"math"
|
||||
"os"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Unmarshaler is the interface implemented by objects that can unmarshal a
|
||||
// TOML description of themselves.
|
||||
type Unmarshaler interface {
|
||||
UnmarshalTOML(any) error
|
||||
}
|
||||
|
||||
// Unmarshal decodes the contents of data in TOML format into a pointer v.
|
||||
//
|
||||
// See [Decoder] for a description of the decoding process.
|
||||
func Unmarshal(data []byte, v any) error {
|
||||
_, err := NewDecoder(bytes.NewReader(data)).Decode(v)
|
||||
return err
|
||||
}
|
||||
|
||||
// Decode the TOML data in to the pointer v.
|
||||
//
|
||||
// See [Decoder] for a description of the decoding process.
|
||||
func Decode(data string, v any) (MetaData, error) {
|
||||
return NewDecoder(strings.NewReader(data)).Decode(v)
|
||||
}
|
||||
|
||||
// DecodeFile reads the contents of a file and decodes it with [Decode].
|
||||
func DecodeFile(path string, v any) (MetaData, error) {
|
||||
fp, err := os.Open(path)
|
||||
if err != nil {
|
||||
return MetaData{}, err
|
||||
}
|
||||
defer fp.Close()
|
||||
return NewDecoder(fp).Decode(v)
|
||||
}
|
||||
|
||||
// DecodeFS reads the contents of a file from [fs.FS] and decodes it with
|
||||
// [Decode].
|
||||
func DecodeFS(fsys fs.FS, path string, v any) (MetaData, error) {
|
||||
fp, err := fsys.Open(path)
|
||||
if err != nil {
|
||||
return MetaData{}, err
|
||||
}
|
||||
defer fp.Close()
|
||||
return NewDecoder(fp).Decode(v)
|
||||
}
|
||||
|
||||
// Primitive is a TOML value that hasn't been decoded into a Go value.
|
||||
//
|
||||
// This type can be used for any value, which will cause decoding to be delayed.
|
||||
// You can use [PrimitiveDecode] to "manually" decode these values.
|
||||
//
|
||||
// NOTE: The underlying representation of a `Primitive` value is subject to
|
||||
// change. Do not rely on it.
|
||||
//
|
||||
// NOTE: Primitive values are still parsed, so using them will only avoid the
|
||||
// overhead of reflection. They can be useful when you don't know the exact type
|
||||
// of TOML data until runtime.
|
||||
type Primitive struct {
|
||||
undecoded any
|
||||
context Key
|
||||
}
|
||||
|
||||
// The significand precision for float32 and float64 is 24 and 53 bits; this is
|
||||
// the range a natural number can be stored in a float without loss of data.
|
||||
const (
|
||||
maxSafeFloat32Int = 16777215 // 2^24-1
|
||||
maxSafeFloat64Int = int64(9007199254740991) // 2^53-1
|
||||
)
|
||||
|
||||
// Decoder decodes TOML data.
|
||||
//
|
||||
// TOML tables correspond to Go structs or maps; they can be used
|
||||
// interchangeably, but structs offer better type safety.
|
||||
//
|
||||
// TOML table arrays correspond to either a slice of structs or a slice of maps.
|
||||
//
|
||||
// TOML datetimes correspond to [time.Time]. Local datetimes are parsed in the
|
||||
// local timezone.
|
||||
//
|
||||
// [time.Duration] types are treated as nanoseconds if the TOML value is an
|
||||
// integer, or they're parsed with time.ParseDuration() if they're strings.
|
||||
//
|
||||
// All other TOML types (float, string, int, bool and array) correspond to the
|
||||
// obvious Go types.
|
||||
//
|
||||
// An exception to the above rules is if a type implements the TextUnmarshaler
|
||||
// interface, in which case any primitive TOML value (floats, strings, integers,
|
||||
// booleans, datetimes) will be converted to a []byte and given to the value's
|
||||
// UnmarshalText method. See the Unmarshaler example for a demonstration with
|
||||
// email addresses.
|
||||
//
|
||||
// # Key mapping
|
||||
//
|
||||
// TOML keys can map to either keys in a Go map or field names in a Go struct.
|
||||
// The special `toml` struct tag can be used to map TOML keys to struct fields
|
||||
// that don't match the key name exactly (see the example). A case insensitive
|
||||
// match to struct names will be tried if an exact match can't be found.
|
||||
//
|
||||
// The mapping between TOML values and Go values is loose. That is, there may
|
||||
// exist TOML values that cannot be placed into your representation, and there
|
||||
// may be parts of your representation that do not correspond to TOML values.
|
||||
// This loose mapping can be made stricter by using the IsDefined and/or
|
||||
// Undecoded methods on the MetaData returned.
|
||||
//
|
||||
// This decoder does not handle cyclic types. Decode will not terminate if a
|
||||
// cyclic type is passed.
|
||||
type Decoder struct {
|
||||
r io.Reader
|
||||
}
|
||||
|
||||
// NewDecoder creates a new Decoder.
|
||||
func NewDecoder(r io.Reader) *Decoder {
|
||||
return &Decoder{r: r}
|
||||
}
|
||||
|
||||
var (
|
||||
unmarshalToml = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
|
||||
unmarshalText = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
|
||||
primitiveType = reflect.TypeOf((*Primitive)(nil)).Elem()
|
||||
)
|
||||
|
||||
// Decode TOML data in to the pointer `v`.
|
||||
func (dec *Decoder) Decode(v any) (MetaData, error) {
|
||||
rv := reflect.ValueOf(v)
|
||||
if rv.Kind() != reflect.Ptr {
|
||||
s := "%q"
|
||||
if reflect.TypeOf(v) == nil {
|
||||
s = "%v"
|
||||
}
|
||||
|
||||
return MetaData{}, fmt.Errorf("toml: cannot decode to non-pointer "+s, reflect.TypeOf(v))
|
||||
}
|
||||
if rv.IsNil() {
|
||||
return MetaData{}, fmt.Errorf("toml: cannot decode to nil value of %q", reflect.TypeOf(v))
|
||||
}
|
||||
|
||||
// Check if this is a supported type: struct, map, any, or something that
|
||||
// implements UnmarshalTOML or UnmarshalText.
|
||||
rv = indirect(rv)
|
||||
rt := rv.Type()
|
||||
if rv.Kind() != reflect.Struct && rv.Kind() != reflect.Map &&
|
||||
!(rv.Kind() == reflect.Interface && rv.NumMethod() == 0) &&
|
||||
!rt.Implements(unmarshalToml) && !rt.Implements(unmarshalText) {
|
||||
return MetaData{}, fmt.Errorf("toml: cannot decode to type %s", rt)
|
||||
}
|
||||
|
||||
// TODO: parser should read from io.Reader? Or at the very least, make it
|
||||
// read from []byte rather than string
|
||||
data, err := io.ReadAll(dec.r)
|
||||
if err != nil {
|
||||
return MetaData{}, err
|
||||
}
|
||||
|
||||
p, err := parse(string(data))
|
||||
if err != nil {
|
||||
return MetaData{}, err
|
||||
}
|
||||
|
||||
md := MetaData{
|
||||
mapping: p.mapping,
|
||||
keyInfo: p.keyInfo,
|
||||
keys: p.ordered,
|
||||
decoded: make(map[string]struct{}, len(p.ordered)),
|
||||
context: nil,
|
||||
data: data,
|
||||
}
|
||||
return md, md.unify(p.mapping, rv)
|
||||
}
|
||||
|
||||
// PrimitiveDecode is just like the other Decode* functions, except it decodes a
|
||||
// TOML value that has already been parsed. Valid primitive values can *only* be
|
||||
// obtained from values filled by the decoder functions, including this method.
|
||||
// (i.e., v may contain more [Primitive] values.)
|
||||
//
|
||||
// Meta data for primitive values is included in the meta data returned by the
|
||||
// Decode* functions with one exception: keys returned by the Undecoded method
|
||||
// will only reflect keys that were decoded. Namely, any keys hidden behind a
|
||||
// Primitive will be considered undecoded. Executing this method will update the
|
||||
// undecoded keys in the meta data. (See the example.)
|
||||
func (md *MetaData) PrimitiveDecode(primValue Primitive, v any) error {
|
||||
md.context = primValue.context
|
||||
defer func() { md.context = nil }()
|
||||
return md.unify(primValue.undecoded, rvalue(v))
|
||||
}
|
||||
|
||||
// markDecodedRecursive is a helper to mark any key under the given tmap as
|
||||
// decoded, recursing as needed
|
||||
func markDecodedRecursive(md *MetaData, tmap map[string]any) {
|
||||
for key := range tmap {
|
||||
md.decoded[md.context.add(key).String()] = struct{}{}
|
||||
if tmap, ok := tmap[key].(map[string]any); ok {
|
||||
md.context = append(md.context, key)
|
||||
markDecodedRecursive(md, tmap)
|
||||
md.context = md.context[0 : len(md.context)-1]
|
||||
}
|
||||
if tarr, ok := tmap[key].([]map[string]any); ok {
|
||||
for _, elm := range tarr {
|
||||
md.context = append(md.context, key)
|
||||
markDecodedRecursive(md, elm)
|
||||
md.context = md.context[0 : len(md.context)-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// unify performs a sort of type unification based on the structure of `rv`,
|
||||
// which is the client representation.
|
||||
//
|
||||
// Any type mismatch produces an error. Finding a type that we don't know
|
||||
// how to handle produces an unsupported type error.
|
||||
func (md *MetaData) unify(data any, rv reflect.Value) error {
|
||||
// Special case. Look for a `Primitive` value.
|
||||
// TODO: #76 would make this superfluous after implemented.
|
||||
if rv.Type() == primitiveType {
|
||||
// Save the undecoded data and the key context into the primitive
|
||||
// value.
|
||||
context := make(Key, len(md.context))
|
||||
copy(context, md.context)
|
||||
rv.Set(reflect.ValueOf(Primitive{
|
||||
undecoded: data,
|
||||
context: context,
|
||||
}))
|
||||
return nil
|
||||
}
|
||||
|
||||
rvi := rv.Interface()
|
||||
if v, ok := rvi.(Unmarshaler); ok {
|
||||
err := v.UnmarshalTOML(data)
|
||||
if err != nil {
|
||||
return md.parseErr(err)
|
||||
}
|
||||
// Assume the Unmarshaler decoded everything, so mark all keys under
|
||||
// this table as decoded.
|
||||
if tmap, ok := data.(map[string]any); ok {
|
||||
markDecodedRecursive(md, tmap)
|
||||
}
|
||||
if aot, ok := data.([]map[string]any); ok {
|
||||
for _, tmap := range aot {
|
||||
markDecodedRecursive(md, tmap)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if v, ok := rvi.(encoding.TextUnmarshaler); ok {
|
||||
return md.unifyText(data, v)
|
||||
}
|
||||
|
||||
// TODO:
|
||||
// The behavior here is incorrect whenever a Go type satisfies the
|
||||
// encoding.TextUnmarshaler interface but also corresponds to a TOML hash or
|
||||
// array. In particular, the unmarshaler should only be applied to primitive
|
||||
// TOML values. But at this point, it will be applied to all kinds of values
|
||||
// and produce an incorrect error whenever those values are hashes or arrays
|
||||
// (including arrays of tables).
|
||||
|
||||
k := rv.Kind()
|
||||
|
||||
if k >= reflect.Int && k <= reflect.Uint64 {
|
||||
return md.unifyInt(data, rv)
|
||||
}
|
||||
switch k {
|
||||
case reflect.Struct:
|
||||
return md.unifyStruct(data, rv)
|
||||
case reflect.Map:
|
||||
return md.unifyMap(data, rv)
|
||||
case reflect.Array:
|
||||
return md.unifyArray(data, rv)
|
||||
case reflect.Slice:
|
||||
return md.unifySlice(data, rv)
|
||||
case reflect.String:
|
||||
return md.unifyString(data, rv)
|
||||
case reflect.Bool:
|
||||
return md.unifyBool(data, rv)
|
||||
case reflect.Interface:
|
||||
if rv.NumMethod() > 0 { /// Only empty interfaces are supported.
|
||||
return md.e("unsupported type %s", rv.Type())
|
||||
}
|
||||
return md.unifyAnything(data, rv)
|
||||
case reflect.Float32, reflect.Float64:
|
||||
return md.unifyFloat64(data, rv)
|
||||
}
|
||||
return md.e("unsupported type %s", rv.Kind())
|
||||
}
|
||||
|
||||
func (md *MetaData) unifyStruct(mapping any, rv reflect.Value) error {
|
||||
tmap, ok := mapping.(map[string]any)
|
||||
if !ok {
|
||||
if mapping == nil {
|
||||
return nil
|
||||
}
|
||||
return md.e("type mismatch for %s: expected table but found %s", rv.Type().String(), fmtType(mapping))
|
||||
}
|
||||
|
||||
for key, datum := range tmap {
|
||||
var f *field
|
||||
fields := cachedTypeFields(rv.Type())
|
||||
for i := range fields {
|
||||
ff := &fields[i]
|
||||
if ff.name == key {
|
||||
f = ff
|
||||
break
|
||||
}
|
||||
if f == nil && strings.EqualFold(ff.name, key) {
|
||||
f = ff
|
||||
}
|
||||
}
|
||||
if f != nil {
|
||||
subv := rv
|
||||
for _, i := range f.index {
|
||||
subv = indirect(subv.Field(i))
|
||||
}
|
||||
|
||||
if isUnifiable(subv) {
|
||||
md.decoded[md.context.add(key).String()] = struct{}{}
|
||||
md.context = append(md.context, key)
|
||||
|
||||
err := md.unify(datum, subv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
md.context = md.context[0 : len(md.context)-1]
|
||||
} else if f.name != "" {
|
||||
return md.e("cannot write unexported field %s.%s", rv.Type().String(), f.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (md *MetaData) unifyMap(mapping any, rv reflect.Value) error {
|
||||
keyType := rv.Type().Key().Kind()
|
||||
if keyType != reflect.String && keyType != reflect.Interface {
|
||||
return fmt.Errorf("toml: cannot decode to a map with non-string key type (%s in %q)",
|
||||
keyType, rv.Type())
|
||||
}
|
||||
|
||||
tmap, ok := mapping.(map[string]any)
|
||||
if !ok {
|
||||
if tmap == nil {
|
||||
return nil
|
||||
}
|
||||
return md.badtype("map", mapping)
|
||||
}
|
||||
if rv.IsNil() {
|
||||
rv.Set(reflect.MakeMap(rv.Type()))
|
||||
}
|
||||
for k, v := range tmap {
|
||||
md.decoded[md.context.add(k).String()] = struct{}{}
|
||||
md.context = append(md.context, k)
|
||||
|
||||
rvval := reflect.Indirect(reflect.New(rv.Type().Elem()))
|
||||
|
||||
err := md.unify(v, indirect(rvval))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
md.context = md.context[0 : len(md.context)-1]
|
||||
|
||||
rvkey := indirect(reflect.New(rv.Type().Key()))
|
||||
|
||||
switch keyType {
|
||||
case reflect.Interface:
|
||||
rvkey.Set(reflect.ValueOf(k))
|
||||
case reflect.String:
|
||||
rvkey.SetString(k)
|
||||
}
|
||||
|
||||
rv.SetMapIndex(rvkey, rvval)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (md *MetaData) unifyArray(data any, rv reflect.Value) error {
|
||||
datav := reflect.ValueOf(data)
|
||||
if datav.Kind() != reflect.Slice {
|
||||
if !datav.IsValid() {
|
||||
return nil
|
||||
}
|
||||
return md.badtype("slice", data)
|
||||
}
|
||||
if l := datav.Len(); l != rv.Len() {
|
||||
return md.e("expected array length %d; got TOML array of length %d", rv.Len(), l)
|
||||
}
|
||||
return md.unifySliceArray(datav, rv)
|
||||
}
|
||||
|
||||
func (md *MetaData) unifySlice(data any, rv reflect.Value) error {
|
||||
datav := reflect.ValueOf(data)
|
||||
if datav.Kind() != reflect.Slice {
|
||||
if !datav.IsValid() {
|
||||
return nil
|
||||
}
|
||||
return md.badtype("slice", data)
|
||||
}
|
||||
n := datav.Len()
|
||||
if rv.IsNil() || rv.Cap() < n {
|
||||
rv.Set(reflect.MakeSlice(rv.Type(), n, n))
|
||||
}
|
||||
rv.SetLen(n)
|
||||
return md.unifySliceArray(datav, rv)
|
||||
}
|
||||
|
||||
func (md *MetaData) unifySliceArray(data, rv reflect.Value) error {
|
||||
l := data.Len()
|
||||
for i := 0; i < l; i++ {
|
||||
err := md.unify(data.Index(i).Interface(), indirect(rv.Index(i)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (md *MetaData) unifyString(data any, rv reflect.Value) error {
|
||||
_, ok := rv.Interface().(json.Number)
|
||||
if ok {
|
||||
if i, ok := data.(int64); ok {
|
||||
rv.SetString(strconv.FormatInt(i, 10))
|
||||
} else if f, ok := data.(float64); ok {
|
||||
rv.SetString(strconv.FormatFloat(f, 'g', -1, 64))
|
||||
} else {
|
||||
return md.badtype("string", data)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if s, ok := data.(string); ok {
|
||||
rv.SetString(s)
|
||||
return nil
|
||||
}
|
||||
return md.badtype("string", data)
|
||||
}
|
||||
|
||||
func (md *MetaData) unifyFloat64(data any, rv reflect.Value) error {
|
||||
rvk := rv.Kind()
|
||||
|
||||
if num, ok := data.(float64); ok {
|
||||
switch rvk {
|
||||
case reflect.Float32:
|
||||
if num < -math.MaxFloat32 || num > math.MaxFloat32 {
|
||||
return md.parseErr(errParseRange{i: num, size: rvk.String()})
|
||||
}
|
||||
fallthrough
|
||||
case reflect.Float64:
|
||||
rv.SetFloat(num)
|
||||
default:
|
||||
panic("bug")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if num, ok := data.(int64); ok {
|
||||
if (rvk == reflect.Float32 && (num < -maxSafeFloat32Int || num > maxSafeFloat32Int)) ||
|
||||
(rvk == reflect.Float64 && (num < -maxSafeFloat64Int || num > maxSafeFloat64Int)) {
|
||||
return md.parseErr(errUnsafeFloat{i: num, size: rvk.String()})
|
||||
}
|
||||
rv.SetFloat(float64(num))
|
||||
return nil
|
||||
}
|
||||
|
||||
return md.badtype("float", data)
|
||||
}
|
||||
|
||||
func (md *MetaData) unifyInt(data any, rv reflect.Value) error {
|
||||
_, ok := rv.Interface().(time.Duration)
|
||||
if ok {
|
||||
// Parse as string duration, and fall back to regular integer parsing
|
||||
// (as nanosecond) if this is not a string.
|
||||
if s, ok := data.(string); ok {
|
||||
dur, err := time.ParseDuration(s)
|
||||
if err != nil {
|
||||
return md.parseErr(errParseDuration{s})
|
||||
}
|
||||
rv.SetInt(int64(dur))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
num, ok := data.(int64)
|
||||
if !ok {
|
||||
return md.badtype("integer", data)
|
||||
}
|
||||
|
||||
rvk := rv.Kind()
|
||||
switch {
|
||||
case rvk >= reflect.Int && rvk <= reflect.Int64:
|
||||
if (rvk == reflect.Int8 && (num < math.MinInt8 || num > math.MaxInt8)) ||
|
||||
(rvk == reflect.Int16 && (num < math.MinInt16 || num > math.MaxInt16)) ||
|
||||
(rvk == reflect.Int32 && (num < math.MinInt32 || num > math.MaxInt32)) {
|
||||
return md.parseErr(errParseRange{i: num, size: rvk.String()})
|
||||
}
|
||||
rv.SetInt(num)
|
||||
case rvk >= reflect.Uint && rvk <= reflect.Uint64:
|
||||
unum := uint64(num)
|
||||
if rvk == reflect.Uint8 && (num < 0 || unum > math.MaxUint8) ||
|
||||
rvk == reflect.Uint16 && (num < 0 || unum > math.MaxUint16) ||
|
||||
rvk == reflect.Uint32 && (num < 0 || unum > math.MaxUint32) {
|
||||
return md.parseErr(errParseRange{i: num, size: rvk.String()})
|
||||
}
|
||||
rv.SetUint(unum)
|
||||
default:
|
||||
panic("unreachable")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (md *MetaData) unifyBool(data any, rv reflect.Value) error {
|
||||
if b, ok := data.(bool); ok {
|
||||
rv.SetBool(b)
|
||||
return nil
|
||||
}
|
||||
return md.badtype("boolean", data)
|
||||
}
|
||||
|
||||
func (md *MetaData) unifyAnything(data any, rv reflect.Value) error {
|
||||
rv.Set(reflect.ValueOf(data))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (md *MetaData) unifyText(data any, v encoding.TextUnmarshaler) error {
|
||||
var s string
|
||||
switch sdata := data.(type) {
|
||||
case Marshaler:
|
||||
text, err := sdata.MarshalTOML()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s = string(text)
|
||||
case encoding.TextMarshaler:
|
||||
text, err := sdata.MarshalText()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s = string(text)
|
||||
case fmt.Stringer:
|
||||
s = sdata.String()
|
||||
case string:
|
||||
s = sdata
|
||||
case bool:
|
||||
s = fmt.Sprintf("%v", sdata)
|
||||
case int64:
|
||||
s = fmt.Sprintf("%d", sdata)
|
||||
case float64:
|
||||
s = fmt.Sprintf("%f", sdata)
|
||||
default:
|
||||
return md.badtype("primitive (string-like)", data)
|
||||
}
|
||||
if err := v.UnmarshalText([]byte(s)); err != nil {
|
||||
return md.parseErr(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (md *MetaData) badtype(dst string, data any) error {
|
||||
return md.e("incompatible types: TOML value has type %s; destination has type %s", fmtType(data), dst)
|
||||
}
|
||||
|
||||
func (md *MetaData) parseErr(err error) error {
|
||||
k := md.context.String()
|
||||
d := string(md.data)
|
||||
return ParseError{
|
||||
Message: err.Error(),
|
||||
err: err,
|
||||
LastKey: k,
|
||||
Position: md.keyInfo[k].pos.withCol(d),
|
||||
Line: md.keyInfo[k].pos.Line,
|
||||
input: d,
|
||||
}
|
||||
}
|
||||
|
||||
func (md *MetaData) e(format string, args ...any) error {
|
||||
f := "toml: "
|
||||
if len(md.context) > 0 {
|
||||
f = fmt.Sprintf("toml: (last key %q): ", md.context)
|
||||
p := md.keyInfo[md.context.String()].pos
|
||||
if p.Line > 0 {
|
||||
f = fmt.Sprintf("toml: line %d (last key %q): ", p.Line, md.context)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf(f+format, args...)
|
||||
}
|
||||
|
||||
// rvalue returns a reflect.Value of `v`. All pointers are resolved.
|
||||
func rvalue(v any) reflect.Value {
|
||||
return indirect(reflect.ValueOf(v))
|
||||
}
|
||||
|
||||
// indirect returns the value pointed to by a pointer.
|
||||
//
|
||||
// Pointers are followed until the value is not a pointer. New values are
|
||||
// allocated for each nil pointer.
|
||||
//
|
||||
// An exception to this rule is if the value satisfies an interface of interest
|
||||
// to us (like encoding.TextUnmarshaler).
|
||||
func indirect(v reflect.Value) reflect.Value {
|
||||
if v.Kind() != reflect.Ptr {
|
||||
if v.CanSet() {
|
||||
pv := v.Addr()
|
||||
pvi := pv.Interface()
|
||||
if _, ok := pvi.(encoding.TextUnmarshaler); ok {
|
||||
return pv
|
||||
}
|
||||
if _, ok := pvi.(Unmarshaler); ok {
|
||||
return pv
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
if v.IsNil() {
|
||||
v.Set(reflect.New(v.Type().Elem()))
|
||||
}
|
||||
return indirect(reflect.Indirect(v))
|
||||
}
|
||||
|
||||
func isUnifiable(rv reflect.Value) bool {
|
||||
if rv.CanSet() {
|
||||
return true
|
||||
}
|
||||
rvi := rv.Interface()
|
||||
if _, ok := rvi.(encoding.TextUnmarshaler); ok {
|
||||
return true
|
||||
}
|
||||
if _, ok := rvi.(Unmarshaler); ok {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// fmt %T with "interface {}" replaced with "any", which is far more readable.
|
||||
func fmtType(t any) string {
|
||||
return strings.ReplaceAll(fmt.Sprintf("%T", t), "interface {}", "any")
|
||||
}
|
||||
29
backend/vendor/github.com/BurntSushi/toml/deprecated.go
generated
vendored
Normal file
29
backend/vendor/github.com/BurntSushi/toml/deprecated.go
generated
vendored
Normal file
@@ -0,0 +1,29 @@
|
||||
package toml
|
||||
|
||||
import (
|
||||
"encoding"
|
||||
"io"
|
||||
)
|
||||
|
||||
// TextMarshaler is an alias for encoding.TextMarshaler.
|
||||
//
|
||||
// Deprecated: use encoding.TextMarshaler
|
||||
type TextMarshaler encoding.TextMarshaler
|
||||
|
||||
// TextUnmarshaler is an alias for encoding.TextUnmarshaler.
|
||||
//
|
||||
// Deprecated: use encoding.TextUnmarshaler
|
||||
type TextUnmarshaler encoding.TextUnmarshaler
|
||||
|
||||
// DecodeReader is an alias for NewDecoder(r).Decode(v).
|
||||
//
|
||||
// Deprecated: use NewDecoder(reader).Decode(&value).
|
||||
func DecodeReader(r io.Reader, v any) (MetaData, error) { return NewDecoder(r).Decode(v) }
|
||||
|
||||
// PrimitiveDecode is an alias for MetaData.PrimitiveDecode().
|
||||
//
|
||||
// Deprecated: use MetaData.PrimitiveDecode.
|
||||
func PrimitiveDecode(primValue Primitive, v any) error {
|
||||
md := MetaData{decoded: make(map[string]struct{})}
|
||||
return md.unify(primValue.undecoded, rvalue(v))
|
||||
}
|
||||
8
backend/vendor/github.com/BurntSushi/toml/doc.go
generated
vendored
Normal file
8
backend/vendor/github.com/BurntSushi/toml/doc.go
generated
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
// Package toml implements decoding and encoding of TOML files.
|
||||
//
|
||||
// This package supports TOML v1.0.0, as specified at https://toml.io
|
||||
//
|
||||
// The github.com/BurntSushi/toml/cmd/tomlv package implements a TOML validator,
|
||||
// and can be used to verify if TOML document is valid. It can also be used to
|
||||
// print the type of each key.
|
||||
package toml
|
||||
789
backend/vendor/github.com/BurntSushi/toml/encode.go
generated
vendored
Normal file
789
backend/vendor/github.com/BurntSushi/toml/encode.go
generated
vendored
Normal file
@@ -0,0 +1,789 @@
|
||||
package toml
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/BurntSushi/toml/internal"
|
||||
)
|
||||
|
||||
type tomlEncodeError struct{ error }
|
||||
|
||||
var (
|
||||
errArrayNilElement = errors.New("toml: cannot encode array with nil element")
|
||||
errNonString = errors.New("toml: cannot encode a map with non-string key type")
|
||||
errNoKey = errors.New("toml: top-level values must be Go maps or structs")
|
||||
errAnything = errors.New("") // used in testing
|
||||
)
|
||||
|
||||
var dblQuotedReplacer = strings.NewReplacer(
|
||||
"\"", "\\\"",
|
||||
"\\", "\\\\",
|
||||
"\x00", `\u0000`,
|
||||
"\x01", `\u0001`,
|
||||
"\x02", `\u0002`,
|
||||
"\x03", `\u0003`,
|
||||
"\x04", `\u0004`,
|
||||
"\x05", `\u0005`,
|
||||
"\x06", `\u0006`,
|
||||
"\x07", `\u0007`,
|
||||
"\b", `\b`,
|
||||
"\t", `\t`,
|
||||
"\n", `\n`,
|
||||
"\x0b", `\u000b`,
|
||||
"\f", `\f`,
|
||||
"\r", `\r`,
|
||||
"\x0e", `\u000e`,
|
||||
"\x0f", `\u000f`,
|
||||
"\x10", `\u0010`,
|
||||
"\x11", `\u0011`,
|
||||
"\x12", `\u0012`,
|
||||
"\x13", `\u0013`,
|
||||
"\x14", `\u0014`,
|
||||
"\x15", `\u0015`,
|
||||
"\x16", `\u0016`,
|
||||
"\x17", `\u0017`,
|
||||
"\x18", `\u0018`,
|
||||
"\x19", `\u0019`,
|
||||
"\x1a", `\u001a`,
|
||||
"\x1b", `\u001b`,
|
||||
"\x1c", `\u001c`,
|
||||
"\x1d", `\u001d`,
|
||||
"\x1e", `\u001e`,
|
||||
"\x1f", `\u001f`,
|
||||
"\x7f", `\u007f`,
|
||||
)
|
||||
|
||||
var (
|
||||
marshalToml = reflect.TypeOf((*Marshaler)(nil)).Elem()
|
||||
marshalText = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
|
||||
timeType = reflect.TypeOf((*time.Time)(nil)).Elem()
|
||||
)
|
||||
|
||||
// Marshaler is the interface implemented by types that can marshal themselves
|
||||
// into valid TOML.
|
||||
type Marshaler interface {
|
||||
MarshalTOML() ([]byte, error)
|
||||
}
|
||||
|
||||
// Marshal returns a TOML representation of the Go value.
|
||||
//
|
||||
// See [Encoder] for a description of the encoding process.
|
||||
func Marshal(v any) ([]byte, error) {
|
||||
buff := new(bytes.Buffer)
|
||||
if err := NewEncoder(buff).Encode(v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buff.Bytes(), nil
|
||||
}
|
||||
|
||||
// Encoder encodes a Go to a TOML document.
|
||||
//
|
||||
// The mapping between Go values and TOML values should be precisely the same as
|
||||
// for [Decode].
|
||||
//
|
||||
// time.Time is encoded as a RFC 3339 string, and time.Duration as its string
|
||||
// representation.
|
||||
//
|
||||
// The [Marshaler] and [encoding.TextMarshaler] interfaces are supported to
|
||||
// encoding the value as custom TOML.
|
||||
//
|
||||
// If you want to write arbitrary binary data then you will need to use
|
||||
// something like base64 since TOML does not have any binary types.
|
||||
//
|
||||
// When encoding TOML hashes (Go maps or structs), keys without any sub-hashes
|
||||
// are encoded first.
|
||||
//
|
||||
// Go maps will be sorted alphabetically by key for deterministic output.
|
||||
//
|
||||
// The toml struct tag can be used to provide the key name; if omitted the
|
||||
// struct field name will be used. If the "omitempty" option is present the
|
||||
// following value will be skipped:
|
||||
//
|
||||
// - arrays, slices, maps, and string with len of 0
|
||||
// - struct with all zero values
|
||||
// - bool false
|
||||
//
|
||||
// If omitzero is given all int and float types with a value of 0 will be
|
||||
// skipped.
|
||||
//
|
||||
// Encoding Go values without a corresponding TOML representation will return an
|
||||
// error. Examples of this includes maps with non-string keys, slices with nil
|
||||
// elements, embedded non-struct types, and nested slices containing maps or
|
||||
// structs. (e.g. [][]map[string]string is not allowed but []map[string]string
|
||||
// is okay, as is []map[string][]string).
|
||||
//
|
||||
// NOTE: only exported keys are encoded due to the use of reflection. Unexported
|
||||
// keys are silently discarded.
|
||||
type Encoder struct {
|
||||
Indent string // string for a single indentation level; default is two spaces.
|
||||
hasWritten bool // written any output to w yet?
|
||||
w *bufio.Writer
|
||||
}
|
||||
|
||||
// NewEncoder create a new Encoder.
|
||||
func NewEncoder(w io.Writer) *Encoder {
|
||||
return &Encoder{w: bufio.NewWriter(w), Indent: " "}
|
||||
}
|
||||
|
||||
// Encode writes a TOML representation of the Go value to the [Encoder]'s writer.
|
||||
//
|
||||
// An error is returned if the value given cannot be encoded to a valid TOML
|
||||
// document.
|
||||
func (enc *Encoder) Encode(v any) error {
|
||||
rv := eindirect(reflect.ValueOf(v))
|
||||
err := enc.safeEncode(Key([]string{}), rv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return enc.w.Flush()
|
||||
}
|
||||
|
||||
func (enc *Encoder) safeEncode(key Key, rv reflect.Value) (err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
if terr, ok := r.(tomlEncodeError); ok {
|
||||
err = terr.error
|
||||
return
|
||||
}
|
||||
panic(r)
|
||||
}
|
||||
}()
|
||||
enc.encode(key, rv)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (enc *Encoder) encode(key Key, rv reflect.Value) {
|
||||
// If we can marshal the type to text, then we use that. This prevents the
|
||||
// encoder for handling these types as generic structs (or whatever the
|
||||
// underlying type of a TextMarshaler is).
|
||||
switch {
|
||||
case isMarshaler(rv):
|
||||
enc.writeKeyValue(key, rv, false)
|
||||
return
|
||||
case rv.Type() == primitiveType: // TODO: #76 would make this superfluous after implemented.
|
||||
enc.encode(key, reflect.ValueOf(rv.Interface().(Primitive).undecoded))
|
||||
return
|
||||
}
|
||||
|
||||
k := rv.Kind()
|
||||
switch k {
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32,
|
||||
reflect.Int64,
|
||||
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32,
|
||||
reflect.Uint64,
|
||||
reflect.Float32, reflect.Float64, reflect.String, reflect.Bool:
|
||||
enc.writeKeyValue(key, rv, false)
|
||||
case reflect.Array, reflect.Slice:
|
||||
if typeEqual(tomlArrayHash, tomlTypeOfGo(rv)) {
|
||||
enc.eArrayOfTables(key, rv)
|
||||
} else {
|
||||
enc.writeKeyValue(key, rv, false)
|
||||
}
|
||||
case reflect.Interface:
|
||||
if rv.IsNil() {
|
||||
return
|
||||
}
|
||||
enc.encode(key, rv.Elem())
|
||||
case reflect.Map:
|
||||
if rv.IsNil() {
|
||||
return
|
||||
}
|
||||
enc.eTable(key, rv)
|
||||
case reflect.Ptr:
|
||||
if rv.IsNil() {
|
||||
return
|
||||
}
|
||||
enc.encode(key, rv.Elem())
|
||||
case reflect.Struct:
|
||||
enc.eTable(key, rv)
|
||||
default:
|
||||
encPanic(fmt.Errorf("unsupported type for key '%s': %s", key, k))
|
||||
}
|
||||
}
|
||||
|
||||
// eElement encodes any value that can be an array element.
|
||||
func (enc *Encoder) eElement(rv reflect.Value) {
|
||||
switch v := rv.Interface().(type) {
|
||||
case time.Time: // Using TextMarshaler adds extra quotes, which we don't want.
|
||||
format := time.RFC3339Nano
|
||||
switch v.Location() {
|
||||
case internal.LocalDatetime:
|
||||
format = "2006-01-02T15:04:05.999999999"
|
||||
case internal.LocalDate:
|
||||
format = "2006-01-02"
|
||||
case internal.LocalTime:
|
||||
format = "15:04:05.999999999"
|
||||
}
|
||||
switch v.Location() {
|
||||
default:
|
||||
enc.write(v.Format(format))
|
||||
case internal.LocalDatetime, internal.LocalDate, internal.LocalTime:
|
||||
enc.write(v.In(time.UTC).Format(format))
|
||||
}
|
||||
return
|
||||
case Marshaler:
|
||||
s, err := v.MarshalTOML()
|
||||
if err != nil {
|
||||
encPanic(err)
|
||||
}
|
||||
if s == nil {
|
||||
encPanic(errors.New("MarshalTOML returned nil and no error"))
|
||||
}
|
||||
enc.w.Write(s)
|
||||
return
|
||||
case encoding.TextMarshaler:
|
||||
s, err := v.MarshalText()
|
||||
if err != nil {
|
||||
encPanic(err)
|
||||
}
|
||||
if s == nil {
|
||||
encPanic(errors.New("MarshalText returned nil and no error"))
|
||||
}
|
||||
enc.writeQuoted(string(s))
|
||||
return
|
||||
case time.Duration:
|
||||
enc.writeQuoted(v.String())
|
||||
return
|
||||
case json.Number:
|
||||
n, _ := rv.Interface().(json.Number)
|
||||
|
||||
if n == "" { /// Useful zero value.
|
||||
enc.w.WriteByte('0')
|
||||
return
|
||||
} else if v, err := n.Int64(); err == nil {
|
||||
enc.eElement(reflect.ValueOf(v))
|
||||
return
|
||||
} else if v, err := n.Float64(); err == nil {
|
||||
enc.eElement(reflect.ValueOf(v))
|
||||
return
|
||||
}
|
||||
encPanic(fmt.Errorf("unable to convert %q to int64 or float64", n))
|
||||
}
|
||||
|
||||
switch rv.Kind() {
|
||||
case reflect.Ptr:
|
||||
enc.eElement(rv.Elem())
|
||||
return
|
||||
case reflect.String:
|
||||
enc.writeQuoted(rv.String())
|
||||
case reflect.Bool:
|
||||
enc.write(strconv.FormatBool(rv.Bool()))
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
enc.write(strconv.FormatInt(rv.Int(), 10))
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
enc.write(strconv.FormatUint(rv.Uint(), 10))
|
||||
case reflect.Float32:
|
||||
f := rv.Float()
|
||||
if math.IsNaN(f) {
|
||||
if math.Signbit(f) {
|
||||
enc.write("-")
|
||||
}
|
||||
enc.write("nan")
|
||||
} else if math.IsInf(f, 0) {
|
||||
if math.Signbit(f) {
|
||||
enc.write("-")
|
||||
}
|
||||
enc.write("inf")
|
||||
} else {
|
||||
enc.write(floatAddDecimal(strconv.FormatFloat(f, 'g', -1, 32)))
|
||||
}
|
||||
case reflect.Float64:
|
||||
f := rv.Float()
|
||||
if math.IsNaN(f) {
|
||||
if math.Signbit(f) {
|
||||
enc.write("-")
|
||||
}
|
||||
enc.write("nan")
|
||||
} else if math.IsInf(f, 0) {
|
||||
if math.Signbit(f) {
|
||||
enc.write("-")
|
||||
}
|
||||
enc.write("inf")
|
||||
} else {
|
||||
enc.write(floatAddDecimal(strconv.FormatFloat(f, 'g', -1, 64)))
|
||||
}
|
||||
case reflect.Array, reflect.Slice:
|
||||
enc.eArrayOrSliceElement(rv)
|
||||
case reflect.Struct:
|
||||
enc.eStruct(nil, rv, true)
|
||||
case reflect.Map:
|
||||
enc.eMap(nil, rv, true)
|
||||
case reflect.Interface:
|
||||
enc.eElement(rv.Elem())
|
||||
default:
|
||||
encPanic(fmt.Errorf("unexpected type: %s", fmtType(rv.Interface())))
|
||||
}
|
||||
}
|
||||
|
||||
// By the TOML spec, all floats must have a decimal with at least one number on
|
||||
// either side.
|
||||
func floatAddDecimal(fstr string) string {
|
||||
for _, c := range fstr {
|
||||
if c == 'e' { // Exponent syntax
|
||||
return fstr
|
||||
}
|
||||
if c == '.' {
|
||||
return fstr
|
||||
}
|
||||
}
|
||||
return fstr + ".0"
|
||||
}
|
||||
|
||||
func (enc *Encoder) writeQuoted(s string) {
|
||||
enc.write(`"` + dblQuotedReplacer.Replace(s) + `"`)
|
||||
}
|
||||
|
||||
func (enc *Encoder) eArrayOrSliceElement(rv reflect.Value) {
|
||||
length := rv.Len()
|
||||
enc.write("[")
|
||||
for i := 0; i < length; i++ {
|
||||
elem := eindirect(rv.Index(i))
|
||||
enc.eElement(elem)
|
||||
if i != length-1 {
|
||||
enc.write(", ")
|
||||
}
|
||||
}
|
||||
enc.write("]")
|
||||
}
|
||||
|
||||
func (enc *Encoder) eArrayOfTables(key Key, rv reflect.Value) {
|
||||
if len(key) == 0 {
|
||||
encPanic(errNoKey)
|
||||
}
|
||||
for i := 0; i < rv.Len(); i++ {
|
||||
trv := eindirect(rv.Index(i))
|
||||
if isNil(trv) {
|
||||
continue
|
||||
}
|
||||
enc.newline()
|
||||
enc.writef("%s[[%s]]", enc.indentStr(key), key)
|
||||
enc.newline()
|
||||
enc.eMapOrStruct(key, trv, false)
|
||||
}
|
||||
}
|
||||
|
||||
func (enc *Encoder) eTable(key Key, rv reflect.Value) {
|
||||
if len(key) == 1 {
|
||||
// Output an extra newline between top-level tables.
|
||||
// (The newline isn't written if nothing else has been written though.)
|
||||
enc.newline()
|
||||
}
|
||||
if len(key) > 0 {
|
||||
enc.writef("%s[%s]", enc.indentStr(key), key)
|
||||
enc.newline()
|
||||
}
|
||||
enc.eMapOrStruct(key, rv, false)
|
||||
}
|
||||
|
||||
func (enc *Encoder) eMapOrStruct(key Key, rv reflect.Value, inline bool) {
|
||||
switch rv.Kind() {
|
||||
case reflect.Map:
|
||||
enc.eMap(key, rv, inline)
|
||||
case reflect.Struct:
|
||||
enc.eStruct(key, rv, inline)
|
||||
default:
|
||||
// Should never happen?
|
||||
panic("eTable: unhandled reflect.Value Kind: " + rv.Kind().String())
|
||||
}
|
||||
}
|
||||
|
||||
func (enc *Encoder) eMap(key Key, rv reflect.Value, inline bool) {
|
||||
rt := rv.Type()
|
||||
if rt.Key().Kind() != reflect.String {
|
||||
encPanic(errNonString)
|
||||
}
|
||||
|
||||
// Sort keys so that we have deterministic output. And write keys directly
|
||||
// underneath this key first, before writing sub-structs or sub-maps.
|
||||
var mapKeysDirect, mapKeysSub []reflect.Value
|
||||
for _, mapKey := range rv.MapKeys() {
|
||||
if typeIsTable(tomlTypeOfGo(eindirect(rv.MapIndex(mapKey)))) {
|
||||
mapKeysSub = append(mapKeysSub, mapKey)
|
||||
} else {
|
||||
mapKeysDirect = append(mapKeysDirect, mapKey)
|
||||
}
|
||||
}
|
||||
|
||||
writeMapKeys := func(mapKeys []reflect.Value, trailC bool) {
|
||||
sort.Slice(mapKeys, func(i, j int) bool { return mapKeys[i].String() < mapKeys[j].String() })
|
||||
for i, mapKey := range mapKeys {
|
||||
val := eindirect(rv.MapIndex(mapKey))
|
||||
if isNil(val) {
|
||||
continue
|
||||
}
|
||||
|
||||
if inline {
|
||||
enc.writeKeyValue(Key{mapKey.String()}, val, true)
|
||||
if trailC || i != len(mapKeys)-1 {
|
||||
enc.write(", ")
|
||||
}
|
||||
} else {
|
||||
enc.encode(key.add(mapKey.String()), val)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if inline {
|
||||
enc.write("{")
|
||||
}
|
||||
writeMapKeys(mapKeysDirect, len(mapKeysSub) > 0)
|
||||
writeMapKeys(mapKeysSub, false)
|
||||
if inline {
|
||||
enc.write("}")
|
||||
}
|
||||
}
|
||||
|
||||
func pointerTo(t reflect.Type) reflect.Type {
|
||||
if t.Kind() == reflect.Ptr {
|
||||
return pointerTo(t.Elem())
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) {
|
||||
// Write keys for fields directly under this key first, because if we write
|
||||
// a field that creates a new table then all keys under it will be in that
|
||||
// table (not the one we're writing here).
|
||||
//
|
||||
// Fields is a [][]int: for fieldsDirect this always has one entry (the
|
||||
// struct index). For fieldsSub it contains two entries: the parent field
|
||||
// index from tv, and the field indexes for the fields of the sub.
|
||||
var (
|
||||
rt = rv.Type()
|
||||
fieldsDirect, fieldsSub [][]int
|
||||
addFields func(rt reflect.Type, rv reflect.Value, start []int)
|
||||
)
|
||||
addFields = func(rt reflect.Type, rv reflect.Value, start []int) {
|
||||
for i := 0; i < rt.NumField(); i++ {
|
||||
f := rt.Field(i)
|
||||
isEmbed := f.Anonymous && pointerTo(f.Type).Kind() == reflect.Struct
|
||||
if f.PkgPath != "" && !isEmbed { /// Skip unexported fields.
|
||||
continue
|
||||
}
|
||||
opts := getOptions(f.Tag)
|
||||
if opts.skip {
|
||||
continue
|
||||
}
|
||||
|
||||
frv := eindirect(rv.Field(i))
|
||||
|
||||
// Need to make a copy because ... ehm, I don't know why... I guess
|
||||
// allocating a new array can cause it to fail(?)
|
||||
//
|
||||
// Done for: https://github.com/BurntSushi/toml/issues/430
|
||||
// Previously only on 32bit for: https://github.com/BurntSushi/toml/issues/314
|
||||
copyStart := make([]int, len(start))
|
||||
copy(copyStart, start)
|
||||
start = copyStart
|
||||
|
||||
// Treat anonymous struct fields with tag names as though they are
|
||||
// not anonymous, like encoding/json does.
|
||||
//
|
||||
// Non-struct anonymous fields use the normal encoding logic.
|
||||
if isEmbed {
|
||||
if getOptions(f.Tag).name == "" && frv.Kind() == reflect.Struct {
|
||||
addFields(frv.Type(), frv, append(start, f.Index...))
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if typeIsTable(tomlTypeOfGo(frv)) {
|
||||
fieldsSub = append(fieldsSub, append(start, f.Index...))
|
||||
} else {
|
||||
fieldsDirect = append(fieldsDirect, append(start, f.Index...))
|
||||
}
|
||||
}
|
||||
}
|
||||
addFields(rt, rv, nil)
|
||||
|
||||
writeFields := func(fields [][]int, totalFields int) {
|
||||
for _, fieldIndex := range fields {
|
||||
fieldType := rt.FieldByIndex(fieldIndex)
|
||||
fieldVal := rv.FieldByIndex(fieldIndex)
|
||||
|
||||
opts := getOptions(fieldType.Tag)
|
||||
if opts.skip {
|
||||
continue
|
||||
}
|
||||
if opts.omitempty && isEmpty(fieldVal) {
|
||||
continue
|
||||
}
|
||||
|
||||
fieldVal = eindirect(fieldVal)
|
||||
|
||||
if isNil(fieldVal) { /// Don't write anything for nil fields.
|
||||
continue
|
||||
}
|
||||
|
||||
keyName := fieldType.Name
|
||||
if opts.name != "" {
|
||||
keyName = opts.name
|
||||
}
|
||||
|
||||
if opts.omitzero && isZero(fieldVal) {
|
||||
continue
|
||||
}
|
||||
|
||||
if inline {
|
||||
enc.writeKeyValue(Key{keyName}, fieldVal, true)
|
||||
if fieldIndex[0] != totalFields-1 {
|
||||
enc.write(", ")
|
||||
}
|
||||
} else {
|
||||
enc.encode(key.add(keyName), fieldVal)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if inline {
|
||||
enc.write("{")
|
||||
}
|
||||
|
||||
l := len(fieldsDirect) + len(fieldsSub)
|
||||
writeFields(fieldsDirect, l)
|
||||
writeFields(fieldsSub, l)
|
||||
if inline {
|
||||
enc.write("}")
|
||||
}
|
||||
}
|
||||
|
||||
// tomlTypeOfGo returns the TOML type name of the Go value's type.
|
||||
//
|
||||
// It is used to determine whether the types of array elements are mixed (which
|
||||
// is forbidden). If the Go value is nil, then it is illegal for it to be an
|
||||
// array element, and valueIsNil is returned as true.
|
||||
//
|
||||
// The type may be `nil`, which means no concrete TOML type could be found.
|
||||
func tomlTypeOfGo(rv reflect.Value) tomlType {
|
||||
if isNil(rv) || !rv.IsValid() {
|
||||
return nil
|
||||
}
|
||||
|
||||
if rv.Kind() == reflect.Struct {
|
||||
if rv.Type() == timeType {
|
||||
return tomlDatetime
|
||||
}
|
||||
if isMarshaler(rv) {
|
||||
return tomlString
|
||||
}
|
||||
return tomlHash
|
||||
}
|
||||
|
||||
if isMarshaler(rv) {
|
||||
return tomlString
|
||||
}
|
||||
|
||||
switch rv.Kind() {
|
||||
case reflect.Bool:
|
||||
return tomlBool
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32,
|
||||
reflect.Int64,
|
||||
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32,
|
||||
reflect.Uint64:
|
||||
return tomlInteger
|
||||
case reflect.Float32, reflect.Float64:
|
||||
return tomlFloat
|
||||
case reflect.Array, reflect.Slice:
|
||||
if isTableArray(rv) {
|
||||
return tomlArrayHash
|
||||
}
|
||||
return tomlArray
|
||||
case reflect.Ptr, reflect.Interface:
|
||||
return tomlTypeOfGo(rv.Elem())
|
||||
case reflect.String:
|
||||
return tomlString
|
||||
case reflect.Map:
|
||||
return tomlHash
|
||||
default:
|
||||
encPanic(errors.New("unsupported type: " + rv.Kind().String()))
|
||||
panic("unreachable")
|
||||
}
|
||||
}
|
||||
|
||||
func isMarshaler(rv reflect.Value) bool {
|
||||
return rv.Type().Implements(marshalText) || rv.Type().Implements(marshalToml)
|
||||
}
|
||||
|
||||
// isTableArray reports if all entries in the array or slice are a table.
|
||||
func isTableArray(arr reflect.Value) bool {
|
||||
if isNil(arr) || !arr.IsValid() || arr.Len() == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
ret := true
|
||||
for i := 0; i < arr.Len(); i++ {
|
||||
tt := tomlTypeOfGo(eindirect(arr.Index(i)))
|
||||
// Don't allow nil.
|
||||
if tt == nil {
|
||||
encPanic(errArrayNilElement)
|
||||
}
|
||||
|
||||
if ret && !typeEqual(tomlHash, tt) {
|
||||
ret = false
|
||||
}
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
type tagOptions struct {
|
||||
skip bool // "-"
|
||||
name string
|
||||
omitempty bool
|
||||
omitzero bool
|
||||
}
|
||||
|
||||
func getOptions(tag reflect.StructTag) tagOptions {
|
||||
t := tag.Get("toml")
|
||||
if t == "-" {
|
||||
return tagOptions{skip: true}
|
||||
}
|
||||
var opts tagOptions
|
||||
parts := strings.Split(t, ",")
|
||||
opts.name = parts[0]
|
||||
for _, s := range parts[1:] {
|
||||
switch s {
|
||||
case "omitempty":
|
||||
opts.omitempty = true
|
||||
case "omitzero":
|
||||
opts.omitzero = true
|
||||
}
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
func isZero(rv reflect.Value) bool {
|
||||
switch rv.Kind() {
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
return rv.Int() == 0
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
return rv.Uint() == 0
|
||||
case reflect.Float32, reflect.Float64:
|
||||
return rv.Float() == 0.0
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isEmpty(rv reflect.Value) bool {
|
||||
switch rv.Kind() {
|
||||
case reflect.Array, reflect.Slice, reflect.Map, reflect.String:
|
||||
return rv.Len() == 0
|
||||
case reflect.Struct:
|
||||
if rv.Type().Comparable() {
|
||||
return reflect.Zero(rv.Type()).Interface() == rv.Interface()
|
||||
}
|
||||
// Need to also check if all the fields are empty, otherwise something
|
||||
// like this with uncomparable types will always return true:
|
||||
//
|
||||
// type a struct{ field b }
|
||||
// type b struct{ s []string }
|
||||
// s := a{field: b{s: []string{"AAA"}}}
|
||||
for i := 0; i < rv.NumField(); i++ {
|
||||
if !isEmpty(rv.Field(i)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
case reflect.Bool:
|
||||
return !rv.Bool()
|
||||
case reflect.Ptr:
|
||||
return rv.IsNil()
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (enc *Encoder) newline() {
|
||||
if enc.hasWritten {
|
||||
enc.write("\n")
|
||||
}
|
||||
}
|
||||
|
||||
// Write a key/value pair:
|
||||
//
|
||||
// key = <any value>
|
||||
//
|
||||
// This is also used for "k = v" in inline tables; so something like this will
|
||||
// be written in three calls:
|
||||
//
|
||||
// ┌───────────────────┐
|
||||
// │ ┌───┐ ┌────┐│
|
||||
// v v v v vv
|
||||
// key = {k = 1, k2 = 2}
|
||||
func (enc *Encoder) writeKeyValue(key Key, val reflect.Value, inline bool) {
|
||||
/// Marshaler used on top-level document; call eElement() to just call
|
||||
/// Marshal{TOML,Text}.
|
||||
if len(key) == 0 {
|
||||
enc.eElement(val)
|
||||
return
|
||||
}
|
||||
enc.writef("%s%s = ", enc.indentStr(key), key.maybeQuoted(len(key)-1))
|
||||
enc.eElement(val)
|
||||
if !inline {
|
||||
enc.newline()
|
||||
}
|
||||
}
|
||||
|
||||
func (enc *Encoder) write(s string) {
|
||||
_, err := enc.w.WriteString(s)
|
||||
if err != nil {
|
||||
encPanic(err)
|
||||
}
|
||||
enc.hasWritten = true
|
||||
}
|
||||
|
||||
func (enc *Encoder) writef(format string, v ...any) {
|
||||
_, err := fmt.Fprintf(enc.w, format, v...)
|
||||
if err != nil {
|
||||
encPanic(err)
|
||||
}
|
||||
enc.hasWritten = true
|
||||
}
|
||||
|
||||
func (enc *Encoder) indentStr(key Key) string {
|
||||
return strings.Repeat(enc.Indent, len(key)-1)
|
||||
}
|
||||
|
||||
func encPanic(err error) {
|
||||
panic(tomlEncodeError{err})
|
||||
}
|
||||
|
||||
// Resolve any level of pointers to the actual value (e.g. **string → string).
|
||||
func eindirect(v reflect.Value) reflect.Value {
|
||||
if v.Kind() != reflect.Ptr && v.Kind() != reflect.Interface {
|
||||
if isMarshaler(v) {
|
||||
return v
|
||||
}
|
||||
if v.CanAddr() { /// Special case for marshalers; see #358.
|
||||
if pv := v.Addr(); isMarshaler(pv) {
|
||||
return pv
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
if v.IsNil() {
|
||||
return v
|
||||
}
|
||||
|
||||
return eindirect(v.Elem())
|
||||
}
|
||||
|
||||
func isNil(rv reflect.Value) bool {
|
||||
switch rv.Kind() {
|
||||
case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
|
||||
return rv.IsNil()
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
347
backend/vendor/github.com/BurntSushi/toml/error.go
generated
vendored
Normal file
347
backend/vendor/github.com/BurntSushi/toml/error.go
generated
vendored
Normal file
@@ -0,0 +1,347 @@
|
||||
package toml
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ParseError is returned when there is an error parsing the TOML syntax such as
|
||||
// invalid syntax, duplicate keys, etc.
|
||||
//
|
||||
// In addition to the error message itself, you can also print detailed location
|
||||
// information with context by using [ErrorWithPosition]:
|
||||
//
|
||||
// toml: error: Key 'fruit' was already created and cannot be used as an array.
|
||||
//
|
||||
// At line 4, column 2-7:
|
||||
//
|
||||
// 2 | fruit = []
|
||||
// 3 |
|
||||
// 4 | [[fruit]] # Not allowed
|
||||
// ^^^^^
|
||||
//
|
||||
// [ErrorWithUsage] can be used to print the above with some more detailed usage
|
||||
// guidance:
|
||||
//
|
||||
// toml: error: newlines not allowed within inline tables
|
||||
//
|
||||
// At line 1, column 18:
|
||||
//
|
||||
// 1 | x = [{ key = 42 #
|
||||
// ^
|
||||
//
|
||||
// Error help:
|
||||
//
|
||||
// Inline tables must always be on a single line:
|
||||
//
|
||||
// table = {key = 42, second = 43}
|
||||
//
|
||||
// It is invalid to split them over multiple lines like so:
|
||||
//
|
||||
// # INVALID
|
||||
// table = {
|
||||
// key = 42,
|
||||
// second = 43
|
||||
// }
|
||||
//
|
||||
// Use regular for this:
|
||||
//
|
||||
// [table]
|
||||
// key = 42
|
||||
// second = 43
|
||||
type ParseError struct {
|
||||
Message string // Short technical message.
|
||||
Usage string // Longer message with usage guidance; may be blank.
|
||||
Position Position // Position of the error
|
||||
LastKey string // Last parsed key, may be blank.
|
||||
|
||||
// Line the error occurred.
|
||||
//
|
||||
// Deprecated: use [Position].
|
||||
Line int
|
||||
|
||||
err error
|
||||
input string
|
||||
}
|
||||
|
||||
// Position of an error.
|
||||
type Position struct {
|
||||
Line int // Line number, starting at 1.
|
||||
Col int // Error column, starting at 1.
|
||||
Start int // Start of error, as byte offset starting at 0.
|
||||
Len int // Length of the error in bytes.
|
||||
}
|
||||
|
||||
func (p Position) withCol(tomlFile string) Position {
|
||||
var (
|
||||
pos int
|
||||
lines = strings.Split(tomlFile, "\n")
|
||||
)
|
||||
for i := range lines {
|
||||
ll := len(lines[i]) + 1 // +1 for the removed newline
|
||||
if pos+ll >= p.Start {
|
||||
p.Col = p.Start - pos + 1
|
||||
if p.Col < 1 { // Should never happen, but just in case.
|
||||
p.Col = 1
|
||||
}
|
||||
break
|
||||
}
|
||||
pos += ll
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (pe ParseError) Error() string {
|
||||
if pe.LastKey == "" {
|
||||
return fmt.Sprintf("toml: line %d: %s", pe.Position.Line, pe.Message)
|
||||
}
|
||||
return fmt.Sprintf("toml: line %d (last key %q): %s",
|
||||
pe.Position.Line, pe.LastKey, pe.Message)
|
||||
}
|
||||
|
||||
// ErrorWithPosition returns the error with detailed location context.
|
||||
//
|
||||
// See the documentation on [ParseError].
|
||||
func (pe ParseError) ErrorWithPosition() string {
|
||||
if pe.input == "" { // Should never happen, but just in case.
|
||||
return pe.Error()
|
||||
}
|
||||
|
||||
// TODO: don't show control characters as literals? This may not show up
|
||||
// well everywhere.
|
||||
|
||||
var (
|
||||
lines = strings.Split(pe.input, "\n")
|
||||
b = new(strings.Builder)
|
||||
)
|
||||
if pe.Position.Len == 1 {
|
||||
fmt.Fprintf(b, "toml: error: %s\n\nAt line %d, column %d:\n\n",
|
||||
pe.Message, pe.Position.Line, pe.Position.Col)
|
||||
} else {
|
||||
fmt.Fprintf(b, "toml: error: %s\n\nAt line %d, column %d-%d:\n\n",
|
||||
pe.Message, pe.Position.Line, pe.Position.Col, pe.Position.Col+pe.Position.Len-1)
|
||||
}
|
||||
if pe.Position.Line > 2 {
|
||||
fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-2, expandTab(lines[pe.Position.Line-3]))
|
||||
}
|
||||
if pe.Position.Line > 1 {
|
||||
fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-1, expandTab(lines[pe.Position.Line-2]))
|
||||
}
|
||||
|
||||
/// Expand tabs, so that the ^^^s are at the correct position, but leave
|
||||
/// "column 10-13" intact. Adjusting this to the visual column would be
|
||||
/// better, but we don't know the tabsize of the user in their editor, which
|
||||
/// can be 8, 4, 2, or something else. We can't know. So leaving it as the
|
||||
/// character index is probably the "most correct".
|
||||
expanded := expandTab(lines[pe.Position.Line-1])
|
||||
diff := len(expanded) - len(lines[pe.Position.Line-1])
|
||||
|
||||
fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line, expanded)
|
||||
fmt.Fprintf(b, "% 10s%s%s\n", "", strings.Repeat(" ", pe.Position.Col-1+diff), strings.Repeat("^", pe.Position.Len))
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// ErrorWithUsage returns the error with detailed location context and usage
|
||||
// guidance.
|
||||
//
|
||||
// See the documentation on [ParseError].
|
||||
func (pe ParseError) ErrorWithUsage() string {
|
||||
m := pe.ErrorWithPosition()
|
||||
if u, ok := pe.err.(interface{ Usage() string }); ok && u.Usage() != "" {
|
||||
lines := strings.Split(strings.TrimSpace(u.Usage()), "\n")
|
||||
for i := range lines {
|
||||
if lines[i] != "" {
|
||||
lines[i] = " " + lines[i]
|
||||
}
|
||||
}
|
||||
return m + "Error help:\n\n" + strings.Join(lines, "\n") + "\n"
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func expandTab(s string) string {
|
||||
var (
|
||||
b strings.Builder
|
||||
l int
|
||||
fill = func(n int) string {
|
||||
b := make([]byte, n)
|
||||
for i := range b {
|
||||
b[i] = ' '
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
)
|
||||
b.Grow(len(s))
|
||||
for _, r := range s {
|
||||
switch r {
|
||||
case '\t':
|
||||
tw := 8 - l%8
|
||||
b.WriteString(fill(tw))
|
||||
l += tw
|
||||
default:
|
||||
b.WriteRune(r)
|
||||
l += 1
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
type (
|
||||
errLexControl struct{ r rune }
|
||||
errLexEscape struct{ r rune }
|
||||
errLexUTF8 struct{ b byte }
|
||||
errParseDate struct{ v string }
|
||||
errLexInlineTableNL struct{}
|
||||
errLexStringNL struct{}
|
||||
errParseRange struct {
|
||||
i any // int or float
|
||||
size string // "int64", "uint16", etc.
|
||||
}
|
||||
errUnsafeFloat struct {
|
||||
i interface{} // float32 or float64
|
||||
size string // "float32" or "float64"
|
||||
}
|
||||
errParseDuration struct{ d string }
|
||||
)
|
||||
|
||||
func (e errLexControl) Error() string {
|
||||
return fmt.Sprintf("TOML files cannot contain control characters: '0x%02x'", e.r)
|
||||
}
|
||||
func (e errLexControl) Usage() string { return "" }
|
||||
|
||||
func (e errLexEscape) Error() string { return fmt.Sprintf(`invalid escape in string '\%c'`, e.r) }
|
||||
func (e errLexEscape) Usage() string { return usageEscape }
|
||||
func (e errLexUTF8) Error() string { return fmt.Sprintf("invalid UTF-8 byte: 0x%02x", e.b) }
|
||||
func (e errLexUTF8) Usage() string { return "" }
|
||||
func (e errParseDate) Error() string { return fmt.Sprintf("invalid datetime: %q", e.v) }
|
||||
func (e errParseDate) Usage() string { return usageDate }
|
||||
func (e errLexInlineTableNL) Error() string { return "newlines not allowed within inline tables" }
|
||||
func (e errLexInlineTableNL) Usage() string { return usageInlineNewline }
|
||||
func (e errLexStringNL) Error() string { return "strings cannot contain newlines" }
|
||||
func (e errLexStringNL) Usage() string { return usageStringNewline }
|
||||
func (e errParseRange) Error() string { return fmt.Sprintf("%v is out of range for %s", e.i, e.size) }
|
||||
func (e errParseRange) Usage() string { return usageIntOverflow }
|
||||
func (e errUnsafeFloat) Error() string {
|
||||
return fmt.Sprintf("%v is out of the safe %s range", e.i, e.size)
|
||||
}
|
||||
func (e errUnsafeFloat) Usage() string { return usageUnsafeFloat }
|
||||
func (e errParseDuration) Error() string { return fmt.Sprintf("invalid duration: %q", e.d) }
|
||||
func (e errParseDuration) Usage() string { return usageDuration }
|
||||
|
||||
const usageEscape = `
|
||||
A '\' inside a "-delimited string is interpreted as an escape character.
|
||||
|
||||
The following escape sequences are supported:
|
||||
\b, \t, \n, \f, \r, \", \\, \uXXXX, and \UXXXXXXXX
|
||||
|
||||
To prevent a '\' from being recognized as an escape character, use either:
|
||||
|
||||
- a ' or '''-delimited string; escape characters aren't processed in them; or
|
||||
- write two backslashes to get a single backslash: '\\'.
|
||||
|
||||
If you're trying to add a Windows path (e.g. "C:\Users\martin") then using '/'
|
||||
instead of '\' will usually also work: "C:/Users/martin".
|
||||
`
|
||||
|
||||
const usageInlineNewline = `
|
||||
Inline tables must always be on a single line:
|
||||
|
||||
table = {key = 42, second = 43}
|
||||
|
||||
It is invalid to split them over multiple lines like so:
|
||||
|
||||
# INVALID
|
||||
table = {
|
||||
key = 42,
|
||||
second = 43
|
||||
}
|
||||
|
||||
Use regular for this:
|
||||
|
||||
[table]
|
||||
key = 42
|
||||
second = 43
|
||||
`
|
||||
|
||||
const usageStringNewline = `
|
||||
Strings must always be on a single line, and cannot span more than one line:
|
||||
|
||||
# INVALID
|
||||
string = "Hello,
|
||||
world!"
|
||||
|
||||
Instead use """ or ''' to split strings over multiple lines:
|
||||
|
||||
string = """Hello,
|
||||
world!"""
|
||||
`
|
||||
|
||||
const usageIntOverflow = `
|
||||
This number is too large; this may be an error in the TOML, but it can also be a
|
||||
bug in the program that uses too small of an integer.
|
||||
|
||||
The maximum and minimum values are:
|
||||
|
||||
size │ lowest │ highest
|
||||
───────┼────────────────┼──────────────
|
||||
int8 │ -128 │ 127
|
||||
int16 │ -32,768 │ 32,767
|
||||
int32 │ -2,147,483,648 │ 2,147,483,647
|
||||
int64 │ -9.2 × 10¹⁷ │ 9.2 × 10¹⁷
|
||||
uint8 │ 0 │ 255
|
||||
uint16 │ 0 │ 65,535
|
||||
uint32 │ 0 │ 4,294,967,295
|
||||
uint64 │ 0 │ 1.8 × 10¹⁸
|
||||
|
||||
int refers to int32 on 32-bit systems and int64 on 64-bit systems.
|
||||
`
|
||||
|
||||
const usageUnsafeFloat = `
|
||||
This number is outside of the "safe" range for floating point numbers; whole
|
||||
(non-fractional) numbers outside the below range can not always be represented
|
||||
accurately in a float, leading to some loss of accuracy.
|
||||
|
||||
Explicitly mark a number as a fractional unit by adding ".0", which will incur
|
||||
some loss of accuracy; for example:
|
||||
|
||||
f = 2_000_000_000.0
|
||||
|
||||
Accuracy ranges:
|
||||
|
||||
float32 = 16,777,215
|
||||
float64 = 9,007,199,254,740,991
|
||||
`
|
||||
|
||||
const usageDuration = `
|
||||
A duration must be as "number<unit>", without any spaces. Valid units are:
|
||||
|
||||
ns nanoseconds (billionth of a second)
|
||||
us, µs microseconds (millionth of a second)
|
||||
ms milliseconds (thousands of a second)
|
||||
s seconds
|
||||
m minutes
|
||||
h hours
|
||||
|
||||
You can combine multiple units; for example "5m10s" for 5 minutes and 10
|
||||
seconds.
|
||||
`
|
||||
|
||||
const usageDate = `
|
||||
A TOML datetime must be in one of the following formats:
|
||||
|
||||
2006-01-02T15:04:05Z07:00 Date and time, with timezone.
|
||||
2006-01-02T15:04:05 Date and time, but without timezone.
|
||||
2006-01-02 Date without a time or timezone.
|
||||
15:04:05 Just a time, without any timezone.
|
||||
|
||||
Seconds may optionally have a fraction, up to nanosecond precision:
|
||||
|
||||
15:04:05.123
|
||||
15:04:05.856018510
|
||||
`
|
||||
|
||||
// TOML 1.1:
|
||||
// The seconds part in times is optional, and may be omitted:
|
||||
// 2006-01-02T15:04Z07:00
|
||||
// 2006-01-02T15:04
|
||||
// 15:04
|
||||
36
backend/vendor/github.com/BurntSushi/toml/internal/tz.go
generated
vendored
Normal file
36
backend/vendor/github.com/BurntSushi/toml/internal/tz.go
generated
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
package internal
|
||||
|
||||
import "time"
|
||||
|
||||
// Timezones used for local datetime, date, and time TOML types.
|
||||
//
|
||||
// The exact way times and dates without a timezone should be interpreted is not
|
||||
// well-defined in the TOML specification and left to the implementation. These
|
||||
// defaults to current local timezone offset of the computer, but this can be
|
||||
// changed by changing these variables before decoding.
|
||||
//
|
||||
// TODO:
|
||||
// Ideally we'd like to offer people the ability to configure the used timezone
|
||||
// by setting Decoder.Timezone and Encoder.Timezone; however, this is a bit
|
||||
// tricky: the reason we use three different variables for this is to support
|
||||
// round-tripping – without these specific TZ names we wouldn't know which
|
||||
// format to use.
|
||||
//
|
||||
// There isn't a good way to encode this right now though, and passing this sort
|
||||
// of information also ties in to various related issues such as string format
|
||||
// encoding, encoding of comments, etc.
|
||||
//
|
||||
// So, for the time being, just put this in internal until we can write a good
|
||||
// comprehensive API for doing all of this.
|
||||
//
|
||||
// The reason they're exported is because they're referred from in e.g.
|
||||
// internal/tag.
|
||||
//
|
||||
// Note that this behaviour is valid according to the TOML spec as the exact
|
||||
// behaviour is left up to implementations.
|
||||
var (
|
||||
localOffset = func() int { _, o := time.Now().Zone(); return o }()
|
||||
LocalDatetime = time.FixedZone("datetime-local", localOffset)
|
||||
LocalDate = time.FixedZone("date-local", localOffset)
|
||||
LocalTime = time.FixedZone("time-local", localOffset)
|
||||
)
|
||||
1248
backend/vendor/github.com/BurntSushi/toml/lex.go
generated
vendored
Normal file
1248
backend/vendor/github.com/BurntSushi/toml/lex.go
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
145
backend/vendor/github.com/BurntSushi/toml/meta.go
generated
vendored
Normal file
145
backend/vendor/github.com/BurntSushi/toml/meta.go
generated
vendored
Normal file
@@ -0,0 +1,145 @@
|
||||
package toml
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// MetaData allows access to meta information about TOML data that's not
|
||||
// accessible otherwise.
|
||||
//
|
||||
// It allows checking if a key is defined in the TOML data, whether any keys
|
||||
// were undecoded, and the TOML type of a key.
|
||||
type MetaData struct {
|
||||
context Key // Used only during decoding.
|
||||
|
||||
keyInfo map[string]keyInfo
|
||||
mapping map[string]any
|
||||
keys []Key
|
||||
decoded map[string]struct{}
|
||||
data []byte // Input file; for errors.
|
||||
}
|
||||
|
||||
// IsDefined reports if the key exists in the TOML data.
|
||||
//
|
||||
// The key should be specified hierarchically, for example to access the TOML
|
||||
// key "a.b.c" you would use IsDefined("a", "b", "c"). Keys are case sensitive.
|
||||
//
|
||||
// Returns false for an empty key.
|
||||
func (md *MetaData) IsDefined(key ...string) bool {
|
||||
if len(key) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
var (
|
||||
hash map[string]any
|
||||
ok bool
|
||||
hashOrVal any = md.mapping
|
||||
)
|
||||
for _, k := range key {
|
||||
if hash, ok = hashOrVal.(map[string]any); !ok {
|
||||
return false
|
||||
}
|
||||
if hashOrVal, ok = hash[k]; !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Type returns a string representation of the type of the key specified.
|
||||
//
|
||||
// Type will return the empty string if given an empty key or a key that does
|
||||
// not exist. Keys are case sensitive.
|
||||
func (md *MetaData) Type(key ...string) string {
|
||||
if ki, ok := md.keyInfo[Key(key).String()]; ok {
|
||||
return ki.tomlType.typeString()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Keys returns a slice of every key in the TOML data, including key groups.
|
||||
//
|
||||
// Each key is itself a slice, where the first element is the top of the
|
||||
// hierarchy and the last is the most specific. The list will have the same
|
||||
// order as the keys appeared in the TOML data.
|
||||
//
|
||||
// All keys returned are non-empty.
|
||||
func (md *MetaData) Keys() []Key {
|
||||
return md.keys
|
||||
}
|
||||
|
||||
// Undecoded returns all keys that have not been decoded in the order in which
|
||||
// they appear in the original TOML document.
|
||||
//
|
||||
// This includes keys that haven't been decoded because of a [Primitive] value.
|
||||
// Once the Primitive value is decoded, the keys will be considered decoded.
|
||||
//
|
||||
// Also note that decoding into an empty interface will result in no decoding,
|
||||
// and so no keys will be considered decoded.
|
||||
//
|
||||
// In this sense, the Undecoded keys correspond to keys in the TOML document
|
||||
// that do not have a concrete type in your representation.
|
||||
func (md *MetaData) Undecoded() []Key {
|
||||
undecoded := make([]Key, 0, len(md.keys))
|
||||
for _, key := range md.keys {
|
||||
if _, ok := md.decoded[key.String()]; !ok {
|
||||
undecoded = append(undecoded, key)
|
||||
}
|
||||
}
|
||||
return undecoded
|
||||
}
|
||||
|
||||
// Key represents any TOML key, including key groups. Use [MetaData.Keys] to get
|
||||
// values of this type.
|
||||
type Key []string
|
||||
|
||||
func (k Key) String() string {
|
||||
// This is called quite often, so it's a bit funky to make it faster.
|
||||
var b strings.Builder
|
||||
b.Grow(len(k) * 25)
|
||||
outer:
|
||||
for i, kk := range k {
|
||||
if i > 0 {
|
||||
b.WriteByte('.')
|
||||
}
|
||||
if kk == "" {
|
||||
b.WriteString(`""`)
|
||||
} else {
|
||||
for _, r := range kk {
|
||||
// "Inline" isBareKeyChar
|
||||
if !((r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r == '-') {
|
||||
b.WriteByte('"')
|
||||
b.WriteString(dblQuotedReplacer.Replace(kk))
|
||||
b.WriteByte('"')
|
||||
continue outer
|
||||
}
|
||||
}
|
||||
b.WriteString(kk)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (k Key) maybeQuoted(i int) string {
|
||||
if k[i] == "" {
|
||||
return `""`
|
||||
}
|
||||
for _, r := range k[i] {
|
||||
if (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r == '-' {
|
||||
continue
|
||||
}
|
||||
return `"` + dblQuotedReplacer.Replace(k[i]) + `"`
|
||||
}
|
||||
return k[i]
|
||||
}
|
||||
|
||||
// Like append(), but only increase the cap by 1.
|
||||
func (k Key) add(piece string) Key {
|
||||
newKey := make(Key, len(k)+1)
|
||||
copy(newKey, k)
|
||||
newKey[len(k)] = piece
|
||||
return newKey
|
||||
}
|
||||
|
||||
func (k Key) parent() Key { return k[:len(k)-1] } // all except the last piece.
|
||||
func (k Key) last() string { return k[len(k)-1] } // last piece of this key.
|
||||
835
backend/vendor/github.com/BurntSushi/toml/parse.go
generated
vendored
Normal file
835
backend/vendor/github.com/BurntSushi/toml/parse.go
generated
vendored
Normal file
@@ -0,0 +1,835 @@
|
||||
package toml
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/BurntSushi/toml/internal"
|
||||
)
|
||||
|
||||
type parser struct {
|
||||
lx *lexer
|
||||
context Key // Full key for the current hash in scope.
|
||||
currentKey string // Base key name for everything except hashes.
|
||||
pos Position // Current position in the TOML file.
|
||||
|
||||
ordered []Key // List of keys in the order that they appear in the TOML data.
|
||||
|
||||
keyInfo map[string]keyInfo // Map keyname → info about the TOML key.
|
||||
mapping map[string]any // Map keyname → key value.
|
||||
implicits map[string]struct{} // Record implicit keys (e.g. "key.group.names").
|
||||
}
|
||||
|
||||
type keyInfo struct {
|
||||
pos Position
|
||||
tomlType tomlType
|
||||
}
|
||||
|
||||
func parse(data string) (p *parser, err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
if pErr, ok := r.(ParseError); ok {
|
||||
pErr.input = data
|
||||
err = pErr
|
||||
return
|
||||
}
|
||||
panic(r)
|
||||
}
|
||||
}()
|
||||
|
||||
// Read over BOM; do this here as the lexer calls utf8.DecodeRuneInString()
|
||||
// which mangles stuff. UTF-16 BOM isn't strictly valid, but some tools add
|
||||
// it anyway.
|
||||
if strings.HasPrefix(data, "\xff\xfe") || strings.HasPrefix(data, "\xfe\xff") { // UTF-16
|
||||
data = data[2:]
|
||||
} else if strings.HasPrefix(data, "\xef\xbb\xbf") { // UTF-8
|
||||
data = data[3:]
|
||||
}
|
||||
|
||||
// Examine first few bytes for NULL bytes; this probably means it's a UTF-16
|
||||
// file (second byte in surrogate pair being NULL). Again, do this here to
|
||||
// avoid having to deal with UTF-8/16 stuff in the lexer.
|
||||
ex := 6
|
||||
if len(data) < 6 {
|
||||
ex = len(data)
|
||||
}
|
||||
if i := strings.IndexRune(data[:ex], 0); i > -1 {
|
||||
return nil, ParseError{
|
||||
Message: "files cannot contain NULL bytes; probably using UTF-16; TOML files must be UTF-8",
|
||||
Position: Position{Line: 1, Col: 1, Start: i, Len: 1},
|
||||
Line: 1,
|
||||
input: data,
|
||||
}
|
||||
}
|
||||
|
||||
p = &parser{
|
||||
keyInfo: make(map[string]keyInfo),
|
||||
mapping: make(map[string]any),
|
||||
lx: lex(data),
|
||||
ordered: make([]Key, 0),
|
||||
implicits: make(map[string]struct{}),
|
||||
}
|
||||
for {
|
||||
item := p.next()
|
||||
if item.typ == itemEOF {
|
||||
break
|
||||
}
|
||||
p.topLevel(item)
|
||||
}
|
||||
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (p *parser) panicErr(it item, err error) {
|
||||
panic(ParseError{
|
||||
Message: err.Error(),
|
||||
err: err,
|
||||
Position: it.pos.withCol(p.lx.input),
|
||||
Line: it.pos.Len,
|
||||
LastKey: p.current(),
|
||||
})
|
||||
}
|
||||
|
||||
func (p *parser) panicItemf(it item, format string, v ...any) {
|
||||
panic(ParseError{
|
||||
Message: fmt.Sprintf(format, v...),
|
||||
Position: it.pos.withCol(p.lx.input),
|
||||
Line: it.pos.Len,
|
||||
LastKey: p.current(),
|
||||
})
|
||||
}
|
||||
|
||||
func (p *parser) panicf(format string, v ...any) {
|
||||
panic(ParseError{
|
||||
Message: fmt.Sprintf(format, v...),
|
||||
Position: p.pos.withCol(p.lx.input),
|
||||
Line: p.pos.Line,
|
||||
LastKey: p.current(),
|
||||
})
|
||||
}
|
||||
|
||||
func (p *parser) next() item {
|
||||
it := p.lx.nextItem()
|
||||
//fmt.Printf("ITEM %-18s line %-3d │ %q\n", it.typ, it.pos.Line, it.val)
|
||||
if it.typ == itemError {
|
||||
if it.err != nil {
|
||||
panic(ParseError{
|
||||
Message: it.err.Error(),
|
||||
err: it.err,
|
||||
Position: it.pos.withCol(p.lx.input),
|
||||
Line: it.pos.Line,
|
||||
LastKey: p.current(),
|
||||
})
|
||||
}
|
||||
|
||||
p.panicItemf(it, "%s", it.val)
|
||||
}
|
||||
return it
|
||||
}
|
||||
|
||||
func (p *parser) nextPos() item {
|
||||
it := p.next()
|
||||
p.pos = it.pos
|
||||
return it
|
||||
}
|
||||
|
||||
func (p *parser) bug(format string, v ...any) {
|
||||
panic(fmt.Sprintf("BUG: "+format+"\n\n", v...))
|
||||
}
|
||||
|
||||
func (p *parser) expect(typ itemType) item {
|
||||
it := p.next()
|
||||
p.assertEqual(typ, it.typ)
|
||||
return it
|
||||
}
|
||||
|
||||
func (p *parser) assertEqual(expected, got itemType) {
|
||||
if expected != got {
|
||||
p.bug("Expected '%s' but got '%s'.", expected, got)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *parser) topLevel(item item) {
|
||||
switch item.typ {
|
||||
case itemCommentStart: // # ..
|
||||
p.expect(itemText)
|
||||
case itemTableStart: // [ .. ]
|
||||
name := p.nextPos()
|
||||
|
||||
var key Key
|
||||
for ; name.typ != itemTableEnd && name.typ != itemEOF; name = p.next() {
|
||||
key = append(key, p.keyString(name))
|
||||
}
|
||||
p.assertEqual(itemTableEnd, name.typ)
|
||||
|
||||
p.addContext(key, false)
|
||||
p.setType("", tomlHash, item.pos)
|
||||
p.ordered = append(p.ordered, key)
|
||||
case itemArrayTableStart: // [[ .. ]]
|
||||
name := p.nextPos()
|
||||
|
||||
var key Key
|
||||
for ; name.typ != itemArrayTableEnd && name.typ != itemEOF; name = p.next() {
|
||||
key = append(key, p.keyString(name))
|
||||
}
|
||||
p.assertEqual(itemArrayTableEnd, name.typ)
|
||||
|
||||
p.addContext(key, true)
|
||||
p.setType("", tomlArrayHash, item.pos)
|
||||
p.ordered = append(p.ordered, key)
|
||||
case itemKeyStart: // key = ..
|
||||
outerContext := p.context
|
||||
/// Read all the key parts (e.g. 'a' and 'b' in 'a.b')
|
||||
k := p.nextPos()
|
||||
var key Key
|
||||
for ; k.typ != itemKeyEnd && k.typ != itemEOF; k = p.next() {
|
||||
key = append(key, p.keyString(k))
|
||||
}
|
||||
p.assertEqual(itemKeyEnd, k.typ)
|
||||
|
||||
/// The current key is the last part.
|
||||
p.currentKey = key.last()
|
||||
|
||||
/// All the other parts (if any) are the context; need to set each part
|
||||
/// as implicit.
|
||||
context := key.parent()
|
||||
for i := range context {
|
||||
p.addImplicitContext(append(p.context, context[i:i+1]...))
|
||||
}
|
||||
p.ordered = append(p.ordered, p.context.add(p.currentKey))
|
||||
|
||||
/// Set value.
|
||||
vItem := p.next()
|
||||
val, typ := p.value(vItem, false)
|
||||
p.setValue(p.currentKey, val)
|
||||
p.setType(p.currentKey, typ, vItem.pos)
|
||||
|
||||
/// Remove the context we added (preserving any context from [tbl] lines).
|
||||
p.context = outerContext
|
||||
p.currentKey = ""
|
||||
default:
|
||||
p.bug("Unexpected type at top level: %s", item.typ)
|
||||
}
|
||||
}
|
||||
|
||||
// Gets a string for a key (or part of a key in a table name).
|
||||
func (p *parser) keyString(it item) string {
|
||||
switch it.typ {
|
||||
case itemText:
|
||||
return it.val
|
||||
case itemString, itemStringEsc, itemMultilineString,
|
||||
itemRawString, itemRawMultilineString:
|
||||
s, _ := p.value(it, false)
|
||||
return s.(string)
|
||||
default:
|
||||
p.bug("Unexpected key type: %s", it.typ)
|
||||
}
|
||||
panic("unreachable")
|
||||
}
|
||||
|
||||
var datetimeRepl = strings.NewReplacer(
|
||||
"z", "Z",
|
||||
"t", "T",
|
||||
" ", "T")
|
||||
|
||||
// value translates an expected value from the lexer into a Go value wrapped
|
||||
// as an empty interface.
|
||||
func (p *parser) value(it item, parentIsArray bool) (any, tomlType) {
|
||||
switch it.typ {
|
||||
case itemString:
|
||||
return it.val, p.typeOfPrimitive(it)
|
||||
case itemStringEsc:
|
||||
return p.replaceEscapes(it, it.val), p.typeOfPrimitive(it)
|
||||
case itemMultilineString:
|
||||
return p.replaceEscapes(it, p.stripEscapedNewlines(stripFirstNewline(it.val))), p.typeOfPrimitive(it)
|
||||
case itemRawString:
|
||||
return it.val, p.typeOfPrimitive(it)
|
||||
case itemRawMultilineString:
|
||||
return stripFirstNewline(it.val), p.typeOfPrimitive(it)
|
||||
case itemInteger:
|
||||
return p.valueInteger(it)
|
||||
case itemFloat:
|
||||
return p.valueFloat(it)
|
||||
case itemBool:
|
||||
switch it.val {
|
||||
case "true":
|
||||
return true, p.typeOfPrimitive(it)
|
||||
case "false":
|
||||
return false, p.typeOfPrimitive(it)
|
||||
default:
|
||||
p.bug("Expected boolean value, but got '%s'.", it.val)
|
||||
}
|
||||
case itemDatetime:
|
||||
return p.valueDatetime(it)
|
||||
case itemArray:
|
||||
return p.valueArray(it)
|
||||
case itemInlineTableStart:
|
||||
return p.valueInlineTable(it, parentIsArray)
|
||||
default:
|
||||
p.bug("Unexpected value type: %s", it.typ)
|
||||
}
|
||||
panic("unreachable")
|
||||
}
|
||||
|
||||
func (p *parser) valueInteger(it item) (any, tomlType) {
|
||||
if !numUnderscoresOK(it.val) {
|
||||
p.panicItemf(it, "Invalid integer %q: underscores must be surrounded by digits", it.val)
|
||||
}
|
||||
if numHasLeadingZero(it.val) {
|
||||
p.panicItemf(it, "Invalid integer %q: cannot have leading zeroes", it.val)
|
||||
}
|
||||
|
||||
num, err := strconv.ParseInt(it.val, 0, 64)
|
||||
if err != nil {
|
||||
// Distinguish integer values. Normally, it'd be a bug if the lexer
|
||||
// provides an invalid integer, but it's possible that the number is
|
||||
// out of range of valid values (which the lexer cannot determine).
|
||||
// So mark the former as a bug but the latter as a legitimate user
|
||||
// error.
|
||||
if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange {
|
||||
p.panicErr(it, errParseRange{i: it.val, size: "int64"})
|
||||
} else {
|
||||
p.bug("Expected integer value, but got '%s'.", it.val)
|
||||
}
|
||||
}
|
||||
return num, p.typeOfPrimitive(it)
|
||||
}
|
||||
|
||||
func (p *parser) valueFloat(it item) (any, tomlType) {
|
||||
parts := strings.FieldsFunc(it.val, func(r rune) bool {
|
||||
switch r {
|
||||
case '.', 'e', 'E':
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
for _, part := range parts {
|
||||
if !numUnderscoresOK(part) {
|
||||
p.panicItemf(it, "Invalid float %q: underscores must be surrounded by digits", it.val)
|
||||
}
|
||||
}
|
||||
if len(parts) > 0 && numHasLeadingZero(parts[0]) {
|
||||
p.panicItemf(it, "Invalid float %q: cannot have leading zeroes", it.val)
|
||||
}
|
||||
if !numPeriodsOK(it.val) {
|
||||
// As a special case, numbers like '123.' or '1.e2',
|
||||
// which are valid as far as Go/strconv are concerned,
|
||||
// must be rejected because TOML says that a fractional
|
||||
// part consists of '.' followed by 1+ digits.
|
||||
p.panicItemf(it, "Invalid float %q: '.' must be followed by one or more digits", it.val)
|
||||
}
|
||||
val := strings.Replace(it.val, "_", "", -1)
|
||||
signbit := false
|
||||
if val == "+nan" || val == "-nan" {
|
||||
signbit = val == "-nan"
|
||||
val = "nan"
|
||||
}
|
||||
num, err := strconv.ParseFloat(val, 64)
|
||||
if err != nil {
|
||||
if e, ok := err.(*strconv.NumError); ok && e.Err == strconv.ErrRange {
|
||||
p.panicErr(it, errParseRange{i: it.val, size: "float64"})
|
||||
} else {
|
||||
p.panicItemf(it, "Invalid float value: %q", it.val)
|
||||
}
|
||||
}
|
||||
if signbit {
|
||||
num = math.Copysign(num, -1)
|
||||
}
|
||||
return num, p.typeOfPrimitive(it)
|
||||
}
|
||||
|
||||
var dtTypes = []struct {
|
||||
fmt string
|
||||
zone *time.Location
|
||||
}{
|
||||
{time.RFC3339Nano, time.Local},
|
||||
{"2006-01-02T15:04:05.999999999", internal.LocalDatetime},
|
||||
{"2006-01-02", internal.LocalDate},
|
||||
{"15:04:05.999999999", internal.LocalTime},
|
||||
{"2006-01-02T15:04Z07:00", time.Local},
|
||||
{"2006-01-02T15:04", internal.LocalDatetime},
|
||||
{"15:04", internal.LocalTime},
|
||||
}
|
||||
|
||||
func (p *parser) valueDatetime(it item) (any, tomlType) {
|
||||
it.val = datetimeRepl.Replace(it.val)
|
||||
var (
|
||||
t time.Time
|
||||
ok bool
|
||||
err error
|
||||
)
|
||||
for _, dt := range dtTypes {
|
||||
t, err = time.ParseInLocation(dt.fmt, it.val, dt.zone)
|
||||
if err == nil {
|
||||
if missingLeadingZero(it.val, dt.fmt) {
|
||||
p.panicErr(it, errParseDate{it.val})
|
||||
}
|
||||
ok = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
p.panicErr(it, errParseDate{it.val})
|
||||
}
|
||||
return t, p.typeOfPrimitive(it)
|
||||
}
|
||||
|
||||
// Go's time.Parse() will accept numbers without a leading zero; there isn't any
|
||||
// way to require it. https://github.com/golang/go/issues/29911
|
||||
//
|
||||
// Depend on the fact that the separators (- and :) should always be at the same
|
||||
// location.
|
||||
func missingLeadingZero(d, l string) bool {
|
||||
for i, c := range []byte(l) {
|
||||
if c == '.' || c == 'Z' {
|
||||
return false
|
||||
}
|
||||
if (c < '0' || c > '9') && d[i] != c {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *parser) valueArray(it item) (any, tomlType) {
|
||||
p.setType(p.currentKey, tomlArray, it.pos)
|
||||
|
||||
var (
|
||||
// Initialize to a non-nil slice to make it consistent with how S = []
|
||||
// decodes into a non-nil slice inside something like struct { S
|
||||
// []string }. See #338
|
||||
array = make([]any, 0, 2)
|
||||
)
|
||||
for it = p.next(); it.typ != itemArrayEnd; it = p.next() {
|
||||
if it.typ == itemCommentStart {
|
||||
p.expect(itemText)
|
||||
continue
|
||||
}
|
||||
|
||||
val, typ := p.value(it, true)
|
||||
array = append(array, val)
|
||||
|
||||
// XXX: type isn't used here, we need it to record the accurate type
|
||||
// information.
|
||||
//
|
||||
// Not entirely sure how to best store this; could use "key[0]",
|
||||
// "key[1]" notation, or maybe store it on the Array type?
|
||||
_ = typ
|
||||
}
|
||||
return array, tomlArray
|
||||
}
|
||||
|
||||
func (p *parser) valueInlineTable(it item, parentIsArray bool) (any, tomlType) {
|
||||
var (
|
||||
topHash = make(map[string]any)
|
||||
outerContext = p.context
|
||||
outerKey = p.currentKey
|
||||
)
|
||||
|
||||
p.context = append(p.context, p.currentKey)
|
||||
prevContext := p.context
|
||||
p.currentKey = ""
|
||||
|
||||
p.addImplicit(p.context)
|
||||
p.addContext(p.context, parentIsArray)
|
||||
|
||||
/// Loop over all table key/value pairs.
|
||||
for it := p.next(); it.typ != itemInlineTableEnd; it = p.next() {
|
||||
if it.typ == itemCommentStart {
|
||||
p.expect(itemText)
|
||||
continue
|
||||
}
|
||||
|
||||
/// Read all key parts.
|
||||
k := p.nextPos()
|
||||
var key Key
|
||||
for ; k.typ != itemKeyEnd && k.typ != itemEOF; k = p.next() {
|
||||
key = append(key, p.keyString(k))
|
||||
}
|
||||
p.assertEqual(itemKeyEnd, k.typ)
|
||||
|
||||
/// The current key is the last part.
|
||||
p.currentKey = key.last()
|
||||
|
||||
/// All the other parts (if any) are the context; need to set each part
|
||||
/// as implicit.
|
||||
context := key.parent()
|
||||
for i := range context {
|
||||
p.addImplicitContext(append(p.context, context[i:i+1]...))
|
||||
}
|
||||
p.ordered = append(p.ordered, p.context.add(p.currentKey))
|
||||
|
||||
/// Set the value.
|
||||
val, typ := p.value(p.next(), false)
|
||||
p.setValue(p.currentKey, val)
|
||||
p.setType(p.currentKey, typ, it.pos)
|
||||
|
||||
hash := topHash
|
||||
for _, c := range context {
|
||||
h, ok := hash[c]
|
||||
if !ok {
|
||||
h = make(map[string]any)
|
||||
hash[c] = h
|
||||
}
|
||||
hash, ok = h.(map[string]any)
|
||||
if !ok {
|
||||
p.panicf("%q is not a table", p.context)
|
||||
}
|
||||
}
|
||||
hash[p.currentKey] = val
|
||||
|
||||
/// Restore context.
|
||||
p.context = prevContext
|
||||
}
|
||||
p.context = outerContext
|
||||
p.currentKey = outerKey
|
||||
return topHash, tomlHash
|
||||
}
|
||||
|
||||
// numHasLeadingZero checks if this number has leading zeroes, allowing for '0',
|
||||
// +/- signs, and base prefixes.
|
||||
func numHasLeadingZero(s string) bool {
|
||||
if len(s) > 1 && s[0] == '0' && !(s[1] == 'b' || s[1] == 'o' || s[1] == 'x') { // Allow 0b, 0o, 0x
|
||||
return true
|
||||
}
|
||||
if len(s) > 2 && (s[0] == '-' || s[0] == '+') && s[1] == '0' {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// numUnderscoresOK checks whether each underscore in s is surrounded by
|
||||
// characters that are not underscores.
|
||||
func numUnderscoresOK(s string) bool {
|
||||
switch s {
|
||||
case "nan", "+nan", "-nan", "inf", "-inf", "+inf":
|
||||
return true
|
||||
}
|
||||
accept := false
|
||||
for _, r := range s {
|
||||
if r == '_' {
|
||||
if !accept {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// isHex is a superset of all the permissible characters surrounding an
|
||||
// underscore.
|
||||
accept = isHex(r)
|
||||
}
|
||||
return accept
|
||||
}
|
||||
|
||||
// numPeriodsOK checks whether every period in s is followed by a digit.
|
||||
func numPeriodsOK(s string) bool {
|
||||
period := false
|
||||
for _, r := range s {
|
||||
if period && !isDigit(r) {
|
||||
return false
|
||||
}
|
||||
period = r == '.'
|
||||
}
|
||||
return !period
|
||||
}
|
||||
|
||||
// Set the current context of the parser, where the context is either a hash or
|
||||
// an array of hashes, depending on the value of the `array` parameter.
|
||||
//
|
||||
// Establishing the context also makes sure that the key isn't a duplicate, and
|
||||
// will create implicit hashes automatically.
|
||||
func (p *parser) addContext(key Key, array bool) {
|
||||
/// Always start at the top level and drill down for our context.
|
||||
hashContext := p.mapping
|
||||
keyContext := make(Key, 0, len(key)-1)
|
||||
|
||||
/// We only need implicit hashes for the parents.
|
||||
for _, k := range key.parent() {
|
||||
_, ok := hashContext[k]
|
||||
keyContext = append(keyContext, k)
|
||||
|
||||
// No key? Make an implicit hash and move on.
|
||||
if !ok {
|
||||
p.addImplicit(keyContext)
|
||||
hashContext[k] = make(map[string]any)
|
||||
}
|
||||
|
||||
// If the hash context is actually an array of tables, then set
|
||||
// the hash context to the last element in that array.
|
||||
//
|
||||
// Otherwise, it better be a table, since this MUST be a key group (by
|
||||
// virtue of it not being the last element in a key).
|
||||
switch t := hashContext[k].(type) {
|
||||
case []map[string]any:
|
||||
hashContext = t[len(t)-1]
|
||||
case map[string]any:
|
||||
hashContext = t
|
||||
default:
|
||||
p.panicf("Key '%s' was already created as a hash.", keyContext)
|
||||
}
|
||||
}
|
||||
|
||||
p.context = keyContext
|
||||
if array {
|
||||
// If this is the first element for this array, then allocate a new
|
||||
// list of tables for it.
|
||||
k := key.last()
|
||||
if _, ok := hashContext[k]; !ok {
|
||||
hashContext[k] = make([]map[string]any, 0, 4)
|
||||
}
|
||||
|
||||
// Add a new table. But make sure the key hasn't already been used
|
||||
// for something else.
|
||||
if hash, ok := hashContext[k].([]map[string]any); ok {
|
||||
hashContext[k] = append(hash, make(map[string]any))
|
||||
} else {
|
||||
p.panicf("Key '%s' was already created and cannot be used as an array.", key)
|
||||
}
|
||||
} else {
|
||||
p.setValue(key.last(), make(map[string]any))
|
||||
}
|
||||
p.context = append(p.context, key.last())
|
||||
}
|
||||
|
||||
// setValue sets the given key to the given value in the current context.
|
||||
// It will make sure that the key hasn't already been defined, account for
|
||||
// implicit key groups.
|
||||
func (p *parser) setValue(key string, value any) {
|
||||
var (
|
||||
tmpHash any
|
||||
ok bool
|
||||
hash = p.mapping
|
||||
keyContext = make(Key, 0, len(p.context)+1)
|
||||
)
|
||||
for _, k := range p.context {
|
||||
keyContext = append(keyContext, k)
|
||||
if tmpHash, ok = hash[k]; !ok {
|
||||
p.bug("Context for key '%s' has not been established.", keyContext)
|
||||
}
|
||||
switch t := tmpHash.(type) {
|
||||
case []map[string]any:
|
||||
// The context is a table of hashes. Pick the most recent table
|
||||
// defined as the current hash.
|
||||
hash = t[len(t)-1]
|
||||
case map[string]any:
|
||||
hash = t
|
||||
default:
|
||||
p.panicf("Key '%s' has already been defined.", keyContext)
|
||||
}
|
||||
}
|
||||
keyContext = append(keyContext, key)
|
||||
|
||||
if _, ok := hash[key]; ok {
|
||||
// Normally redefining keys isn't allowed, but the key could have been
|
||||
// defined implicitly and it's allowed to be redefined concretely. (See
|
||||
// the `valid/implicit-and-explicit-after.toml` in toml-test)
|
||||
//
|
||||
// But we have to make sure to stop marking it as an implicit. (So that
|
||||
// another redefinition provokes an error.)
|
||||
//
|
||||
// Note that since it has already been defined (as a hash), we don't
|
||||
// want to overwrite it. So our business is done.
|
||||
if p.isArray(keyContext) {
|
||||
if !p.isImplicit(keyContext) {
|
||||
if _, ok := hash[key]; ok {
|
||||
p.panicf("Key '%s' has already been defined.", keyContext)
|
||||
}
|
||||
}
|
||||
p.removeImplicit(keyContext)
|
||||
hash[key] = value
|
||||
return
|
||||
}
|
||||
if p.isImplicit(keyContext) {
|
||||
p.removeImplicit(keyContext)
|
||||
return
|
||||
}
|
||||
// Otherwise, we have a concrete key trying to override a previous key,
|
||||
// which is *always* wrong.
|
||||
p.panicf("Key '%s' has already been defined.", keyContext)
|
||||
}
|
||||
|
||||
hash[key] = value
|
||||
}
|
||||
|
||||
// setType sets the type of a particular value at a given key. It should be
|
||||
// called immediately AFTER setValue.
|
||||
//
|
||||
// Note that if `key` is empty, then the type given will be applied to the
|
||||
// current context (which is either a table or an array of tables).
|
||||
func (p *parser) setType(key string, typ tomlType, pos Position) {
|
||||
keyContext := make(Key, 0, len(p.context)+1)
|
||||
keyContext = append(keyContext, p.context...)
|
||||
if len(key) > 0 { // allow type setting for hashes
|
||||
keyContext = append(keyContext, key)
|
||||
}
|
||||
// Special case to make empty keys ("" = 1) work.
|
||||
// Without it it will set "" rather than `""`.
|
||||
// TODO: why is this needed? And why is this only needed here?
|
||||
if len(keyContext) == 0 {
|
||||
keyContext = Key{""}
|
||||
}
|
||||
p.keyInfo[keyContext.String()] = keyInfo{tomlType: typ, pos: pos}
|
||||
}
|
||||
|
||||
// Implicit keys need to be created when tables are implied in "a.b.c.d = 1" and
|
||||
// "[a.b.c]" (the "a", "b", and "c" hashes are never created explicitly).
|
||||
func (p *parser) addImplicit(key Key) { p.implicits[key.String()] = struct{}{} }
|
||||
func (p *parser) removeImplicit(key Key) { delete(p.implicits, key.String()) }
|
||||
func (p *parser) isImplicit(key Key) bool { _, ok := p.implicits[key.String()]; return ok }
|
||||
func (p *parser) isArray(key Key) bool { return p.keyInfo[key.String()].tomlType == tomlArray }
|
||||
func (p *parser) addImplicitContext(key Key) { p.addImplicit(key); p.addContext(key, false) }
|
||||
|
||||
// current returns the full key name of the current context.
|
||||
func (p *parser) current() string {
|
||||
if len(p.currentKey) == 0 {
|
||||
return p.context.String()
|
||||
}
|
||||
if len(p.context) == 0 {
|
||||
return p.currentKey
|
||||
}
|
||||
return fmt.Sprintf("%s.%s", p.context, p.currentKey)
|
||||
}
|
||||
|
||||
func stripFirstNewline(s string) string {
|
||||
if len(s) > 0 && s[0] == '\n' {
|
||||
return s[1:]
|
||||
}
|
||||
if len(s) > 1 && s[0] == '\r' && s[1] == '\n' {
|
||||
return s[2:]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// stripEscapedNewlines removes whitespace after line-ending backslashes in
|
||||
// multiline strings.
|
||||
//
|
||||
// A line-ending backslash is an unescaped \ followed only by whitespace until
|
||||
// the next newline. After a line-ending backslash, all whitespace is removed
|
||||
// until the next non-whitespace character.
|
||||
func (p *parser) stripEscapedNewlines(s string) string {
|
||||
var (
|
||||
b strings.Builder
|
||||
i int
|
||||
)
|
||||
b.Grow(len(s))
|
||||
for {
|
||||
ix := strings.Index(s[i:], `\`)
|
||||
if ix < 0 {
|
||||
b.WriteString(s)
|
||||
return b.String()
|
||||
}
|
||||
i += ix
|
||||
|
||||
if len(s) > i+1 && s[i+1] == '\\' {
|
||||
// Escaped backslash.
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
// Scan until the next non-whitespace.
|
||||
j := i + 1
|
||||
whitespaceLoop:
|
||||
for ; j < len(s); j++ {
|
||||
switch s[j] {
|
||||
case ' ', '\t', '\r', '\n':
|
||||
default:
|
||||
break whitespaceLoop
|
||||
}
|
||||
}
|
||||
if j == i+1 {
|
||||
// Not a whitespace escape.
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if !strings.Contains(s[i:j], "\n") {
|
||||
// This is not a line-ending backslash. (It's a bad escape sequence,
|
||||
// but we can let replaceEscapes catch it.)
|
||||
i++
|
||||
continue
|
||||
}
|
||||
b.WriteString(s[:i])
|
||||
s = s[j:]
|
||||
i = 0
|
||||
}
|
||||
}
|
||||
|
||||
func (p *parser) replaceEscapes(it item, str string) string {
|
||||
var (
|
||||
b strings.Builder
|
||||
skip = 0
|
||||
)
|
||||
b.Grow(len(str))
|
||||
for i, c := range str {
|
||||
if skip > 0 {
|
||||
skip--
|
||||
continue
|
||||
}
|
||||
if c != '\\' {
|
||||
b.WriteRune(c)
|
||||
continue
|
||||
}
|
||||
|
||||
if i >= len(str) {
|
||||
p.bug("Escape sequence at end of string.")
|
||||
return ""
|
||||
}
|
||||
switch str[i+1] {
|
||||
default:
|
||||
p.bug("Expected valid escape code after \\, but got %q.", str[i+1])
|
||||
case ' ', '\t':
|
||||
p.panicItemf(it, "invalid escape: '\\%c'", str[i+1])
|
||||
case 'b':
|
||||
b.WriteByte(0x08)
|
||||
skip = 1
|
||||
case 't':
|
||||
b.WriteByte(0x09)
|
||||
skip = 1
|
||||
case 'n':
|
||||
b.WriteByte(0x0a)
|
||||
skip = 1
|
||||
case 'f':
|
||||
b.WriteByte(0x0c)
|
||||
skip = 1
|
||||
case 'r':
|
||||
b.WriteByte(0x0d)
|
||||
skip = 1
|
||||
case 'e':
|
||||
b.WriteByte(0x1b)
|
||||
skip = 1
|
||||
case '"':
|
||||
b.WriteByte(0x22)
|
||||
skip = 1
|
||||
case '\\':
|
||||
b.WriteByte(0x5c)
|
||||
skip = 1
|
||||
// The lexer guarantees the correct number of characters are present;
|
||||
// don't need to check here.
|
||||
case 'x':
|
||||
escaped := p.asciiEscapeToUnicode(it, str[i+2:i+4])
|
||||
b.WriteRune(escaped)
|
||||
skip = 3
|
||||
case 'u':
|
||||
escaped := p.asciiEscapeToUnicode(it, str[i+2:i+6])
|
||||
b.WriteRune(escaped)
|
||||
skip = 5
|
||||
case 'U':
|
||||
escaped := p.asciiEscapeToUnicode(it, str[i+2:i+10])
|
||||
b.WriteRune(escaped)
|
||||
skip = 9
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (p *parser) asciiEscapeToUnicode(it item, s string) rune {
|
||||
hex, err := strconv.ParseUint(strings.ToLower(s), 16, 32)
|
||||
if err != nil {
|
||||
p.bug("Could not parse '%s' as a hexadecimal number, but the lexer claims it's OK: %s", s, err)
|
||||
}
|
||||
if !utf8.ValidRune(rune(hex)) {
|
||||
p.panicItemf(it, "Escaped character '\\u%s' is not valid UTF-8.", s)
|
||||
}
|
||||
return rune(hex)
|
||||
}
|
||||
238
backend/vendor/github.com/BurntSushi/toml/type_fields.go
generated
vendored
Normal file
238
backend/vendor/github.com/BurntSushi/toml/type_fields.go
generated
vendored
Normal file
@@ -0,0 +1,238 @@
|
||||
package toml
|
||||
|
||||
// Struct field handling is adapted from code in encoding/json:
|
||||
//
|
||||
// Copyright 2010 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the Go distribution.
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"sort"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// A field represents a single field found in a struct.
|
||||
type field struct {
|
||||
name string // the name of the field (`toml` tag included)
|
||||
tag bool // whether field has a `toml` tag
|
||||
index []int // represents the depth of an anonymous field
|
||||
typ reflect.Type // the type of the field
|
||||
}
|
||||
|
||||
// byName sorts field by name, breaking ties with depth,
|
||||
// then breaking ties with "name came from toml tag", then
|
||||
// breaking ties with index sequence.
|
||||
type byName []field
|
||||
|
||||
func (x byName) Len() int { return len(x) }
|
||||
func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
|
||||
func (x byName) Less(i, j int) bool {
|
||||
if x[i].name != x[j].name {
|
||||
return x[i].name < x[j].name
|
||||
}
|
||||
if len(x[i].index) != len(x[j].index) {
|
||||
return len(x[i].index) < len(x[j].index)
|
||||
}
|
||||
if x[i].tag != x[j].tag {
|
||||
return x[i].tag
|
||||
}
|
||||
return byIndex(x).Less(i, j)
|
||||
}
|
||||
|
||||
// byIndex sorts field by index sequence.
|
||||
type byIndex []field
|
||||
|
||||
func (x byIndex) Len() int { return len(x) }
|
||||
func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
|
||||
func (x byIndex) Less(i, j int) bool {
|
||||
for k, xik := range x[i].index {
|
||||
if k >= len(x[j].index) {
|
||||
return false
|
||||
}
|
||||
if xik != x[j].index[k] {
|
||||
return xik < x[j].index[k]
|
||||
}
|
||||
}
|
||||
return len(x[i].index) < len(x[j].index)
|
||||
}
|
||||
|
||||
// typeFields returns a list of fields that TOML should recognize for the given
|
||||
// type. The algorithm is breadth-first search over the set of structs to
|
||||
// include - the top struct and then any reachable anonymous structs.
|
||||
func typeFields(t reflect.Type) []field {
|
||||
// Anonymous fields to explore at the current level and the next.
|
||||
current := []field{}
|
||||
next := []field{{typ: t}}
|
||||
|
||||
// Count of queued names for current level and the next.
|
||||
var count map[reflect.Type]int
|
||||
var nextCount map[reflect.Type]int
|
||||
|
||||
// Types already visited at an earlier level.
|
||||
visited := map[reflect.Type]bool{}
|
||||
|
||||
// Fields found.
|
||||
var fields []field
|
||||
|
||||
for len(next) > 0 {
|
||||
current, next = next, current[:0]
|
||||
count, nextCount = nextCount, map[reflect.Type]int{}
|
||||
|
||||
for _, f := range current {
|
||||
if visited[f.typ] {
|
||||
continue
|
||||
}
|
||||
visited[f.typ] = true
|
||||
|
||||
// Scan f.typ for fields to include.
|
||||
for i := 0; i < f.typ.NumField(); i++ {
|
||||
sf := f.typ.Field(i)
|
||||
if sf.PkgPath != "" && !sf.Anonymous { // unexported
|
||||
continue
|
||||
}
|
||||
opts := getOptions(sf.Tag)
|
||||
if opts.skip {
|
||||
continue
|
||||
}
|
||||
index := make([]int, len(f.index)+1)
|
||||
copy(index, f.index)
|
||||
index[len(f.index)] = i
|
||||
|
||||
ft := sf.Type
|
||||
if ft.Name() == "" && ft.Kind() == reflect.Ptr {
|
||||
// Follow pointer.
|
||||
ft = ft.Elem()
|
||||
}
|
||||
|
||||
// Record found field and index sequence.
|
||||
if opts.name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct {
|
||||
tagged := opts.name != ""
|
||||
name := opts.name
|
||||
if name == "" {
|
||||
name = sf.Name
|
||||
}
|
||||
fields = append(fields, field{name, tagged, index, ft})
|
||||
if count[f.typ] > 1 {
|
||||
// If there were multiple instances, add a second,
|
||||
// so that the annihilation code will see a duplicate.
|
||||
// It only cares about the distinction between 1 or 2,
|
||||
// so don't bother generating any more copies.
|
||||
fields = append(fields, fields[len(fields)-1])
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Record new anonymous struct to explore in next round.
|
||||
nextCount[ft]++
|
||||
if nextCount[ft] == 1 {
|
||||
f := field{name: ft.Name(), index: index, typ: ft}
|
||||
next = append(next, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sort.Sort(byName(fields))
|
||||
|
||||
// Delete all fields that are hidden by the Go rules for embedded fields,
|
||||
// except that fields with TOML tags are promoted.
|
||||
|
||||
// The fields are sorted in primary order of name, secondary order
|
||||
// of field index length. Loop over names; for each name, delete
|
||||
// hidden fields by choosing the one dominant field that survives.
|
||||
out := fields[:0]
|
||||
for advance, i := 0, 0; i < len(fields); i += advance {
|
||||
// One iteration per name.
|
||||
// Find the sequence of fields with the name of this first field.
|
||||
fi := fields[i]
|
||||
name := fi.name
|
||||
for advance = 1; i+advance < len(fields); advance++ {
|
||||
fj := fields[i+advance]
|
||||
if fj.name != name {
|
||||
break
|
||||
}
|
||||
}
|
||||
if advance == 1 { // Only one field with this name
|
||||
out = append(out, fi)
|
||||
continue
|
||||
}
|
||||
dominant, ok := dominantField(fields[i : i+advance])
|
||||
if ok {
|
||||
out = append(out, dominant)
|
||||
}
|
||||
}
|
||||
|
||||
fields = out
|
||||
sort.Sort(byIndex(fields))
|
||||
|
||||
return fields
|
||||
}
|
||||
|
||||
// dominantField looks through the fields, all of which are known to
|
||||
// have the same name, to find the single field that dominates the
|
||||
// others using Go's embedding rules, modified by the presence of
|
||||
// TOML tags. If there are multiple top-level fields, the boolean
|
||||
// will be false: This condition is an error in Go and we skip all
|
||||
// the fields.
|
||||
func dominantField(fields []field) (field, bool) {
|
||||
// The fields are sorted in increasing index-length order. The winner
|
||||
// must therefore be one with the shortest index length. Drop all
|
||||
// longer entries, which is easy: just truncate the slice.
|
||||
length := len(fields[0].index)
|
||||
tagged := -1 // Index of first tagged field.
|
||||
for i, f := range fields {
|
||||
if len(f.index) > length {
|
||||
fields = fields[:i]
|
||||
break
|
||||
}
|
||||
if f.tag {
|
||||
if tagged >= 0 {
|
||||
// Multiple tagged fields at the same level: conflict.
|
||||
// Return no field.
|
||||
return field{}, false
|
||||
}
|
||||
tagged = i
|
||||
}
|
||||
}
|
||||
if tagged >= 0 {
|
||||
return fields[tagged], true
|
||||
}
|
||||
// All remaining fields have the same length. If there's more than one,
|
||||
// we have a conflict (two fields named "X" at the same level) and we
|
||||
// return no field.
|
||||
if len(fields) > 1 {
|
||||
return field{}, false
|
||||
}
|
||||
return fields[0], true
|
||||
}
|
||||
|
||||
var fieldCache struct {
|
||||
sync.RWMutex
|
||||
m map[reflect.Type][]field
|
||||
}
|
||||
|
||||
// cachedTypeFields is like typeFields but uses a cache to avoid repeated work.
|
||||
func cachedTypeFields(t reflect.Type) []field {
|
||||
fieldCache.RLock()
|
||||
f := fieldCache.m[t]
|
||||
fieldCache.RUnlock()
|
||||
if f != nil {
|
||||
return f
|
||||
}
|
||||
|
||||
// Compute fields without lock.
|
||||
// Might duplicate effort but won't hold other computations back.
|
||||
f = typeFields(t)
|
||||
if f == nil {
|
||||
f = []field{}
|
||||
}
|
||||
|
||||
fieldCache.Lock()
|
||||
if fieldCache.m == nil {
|
||||
fieldCache.m = map[reflect.Type][]field{}
|
||||
}
|
||||
fieldCache.m[t] = f
|
||||
fieldCache.Unlock()
|
||||
return f
|
||||
}
|
||||
65
backend/vendor/github.com/BurntSushi/toml/type_toml.go
generated
vendored
Normal file
65
backend/vendor/github.com/BurntSushi/toml/type_toml.go
generated
vendored
Normal file
@@ -0,0 +1,65 @@
|
||||
package toml
|
||||
|
||||
// tomlType represents any Go type that corresponds to a TOML type.
|
||||
// While the first draft of the TOML spec has a simplistic type system that
|
||||
// probably doesn't need this level of sophistication, we seem to be militating
|
||||
// toward adding real composite types.
|
||||
type tomlType interface {
|
||||
typeString() string
|
||||
}
|
||||
|
||||
// typeEqual accepts any two types and returns true if they are equal.
|
||||
func typeEqual(t1, t2 tomlType) bool {
|
||||
if t1 == nil || t2 == nil {
|
||||
return false
|
||||
}
|
||||
return t1.typeString() == t2.typeString()
|
||||
}
|
||||
|
||||
func typeIsTable(t tomlType) bool {
|
||||
return typeEqual(t, tomlHash) || typeEqual(t, tomlArrayHash)
|
||||
}
|
||||
|
||||
type tomlBaseType string
|
||||
|
||||
func (btype tomlBaseType) typeString() string { return string(btype) }
|
||||
func (btype tomlBaseType) String() string { return btype.typeString() }
|
||||
|
||||
var (
|
||||
tomlInteger tomlBaseType = "Integer"
|
||||
tomlFloat tomlBaseType = "Float"
|
||||
tomlDatetime tomlBaseType = "Datetime"
|
||||
tomlString tomlBaseType = "String"
|
||||
tomlBool tomlBaseType = "Bool"
|
||||
tomlArray tomlBaseType = "Array"
|
||||
tomlHash tomlBaseType = "Hash"
|
||||
tomlArrayHash tomlBaseType = "ArrayHash"
|
||||
)
|
||||
|
||||
// typeOfPrimitive returns a tomlType of any primitive value in TOML.
|
||||
// Primitive values are: Integer, Float, Datetime, String and Bool.
|
||||
//
|
||||
// Passing a lexer item other than the following will cause a BUG message
|
||||
// to occur: itemString, itemBool, itemInteger, itemFloat, itemDatetime.
|
||||
func (p *parser) typeOfPrimitive(lexItem item) tomlType {
|
||||
switch lexItem.typ {
|
||||
case itemInteger:
|
||||
return tomlInteger
|
||||
case itemFloat:
|
||||
return tomlFloat
|
||||
case itemDatetime:
|
||||
return tomlDatetime
|
||||
case itemString, itemStringEsc:
|
||||
return tomlString
|
||||
case itemMultilineString:
|
||||
return tomlString
|
||||
case itemRawString:
|
||||
return tomlString
|
||||
case itemRawMultilineString:
|
||||
return tomlString
|
||||
case itemBool:
|
||||
return tomlBool
|
||||
}
|
||||
p.bug("Cannot infer primitive type of lex item '%s'.", lexItem)
|
||||
panic("unreachable")
|
||||
}
|
||||
16
backend/vendor/github.com/KyleBanks/depth/.gitignore
generated
vendored
Normal file
16
backend/vendor/github.com/KyleBanks/depth/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
# Binaries for programs and plugins
|
||||
*.exe
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
|
||||
# Test binary, build with `go test -c`
|
||||
*.test
|
||||
|
||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||
*.out
|
||||
|
||||
# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736
|
||||
.glide/
|
||||
|
||||
bin/
|
||||
9
backend/vendor/github.com/KyleBanks/depth/.travis.yml
generated
vendored
Normal file
9
backend/vendor/github.com/KyleBanks/depth/.travis.yml
generated
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
language: go
|
||||
sudo: false
|
||||
go:
|
||||
- 1.9.x
|
||||
before_install:
|
||||
- go get github.com/mattn/goveralls
|
||||
script:
|
||||
- $HOME/gopath/bin/goveralls -service=travis-ci
|
||||
#script: go test $(go list ./... | grep -v vendor/)
|
||||
21
backend/vendor/github.com/KyleBanks/depth/LICENSE
generated
vendored
Normal file
21
backend/vendor/github.com/KyleBanks/depth/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 Kyle Banks
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user