settings section
This commit is contained in:
BIN
pkg/.DS_Store
vendored
Normal file
BIN
pkg/.DS_Store
vendored
Normal file
Binary file not shown.
BIN
pkg/client/.DS_Store
vendored
Executable file
BIN
pkg/client/.DS_Store
vendored
Executable file
Binary file not shown.
63
pkg/client/postgresql/postgresql.go
Executable file
63
pkg/client/postgresql/postgresql.go
Executable file
@@ -0,0 +1,63 @@
|
||||
package postgresql
|
||||
|
||||
import (
|
||||
"online-back/internal/config"
|
||||
repeatable "online-back/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
|
||||
}
|
||||
78
pkg/logging/logging.go
Executable file
78
pkg/logging/logging.go
Executable file
@@ -0,0 +1,78 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"runtime"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const pathLog = "./logs/all.log"
|
||||
|
||||
type writerHook struct {
|
||||
Writer []io.Writer
|
||||
LogLevels []logrus.Level
|
||||
}
|
||||
|
||||
func (hook *writerHook) Fire(entry *logrus.Entry) error {
|
||||
line, err := entry.String()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, w := range hook.Writer {
|
||||
if _, err = w.Write([]byte(line)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
l.SetOutput(io.Discard)
|
||||
|
||||
writers := []io.Writer{os.Stdout}
|
||||
if err := os.MkdirAll("logs", 0755); err == nil {
|
||||
if f, err := os.OpenFile(pathLog, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0640); err == nil {
|
||||
writers = append(writers, f)
|
||||
}
|
||||
}
|
||||
|
||||
l.AddHook(&writerHook{
|
||||
Writer: writers,
|
||||
LogLevels: logrus.AllLevels,
|
||||
})
|
||||
l.SetLevel(logrus.TraceLevel)
|
||||
|
||||
e = logrus.NewEntry(l)
|
||||
}
|
||||
79
pkg/utils/utils.go
Executable file
79
pkg/utils/utils.go
Executable file
@@ -0,0 +1,79 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"online-back/internal/config"
|
||||
|
||||
"github.com/golang-jwt/jwt"
|
||||
)
|
||||
|
||||
func DoWithTries(fn func() error, attempts int, delay time.Duration) error {
|
||||
var err error
|
||||
for attempts > 0 {
|
||||
if err = fn(); err == nil {
|
||||
return nil
|
||||
}
|
||||
time.Sleep(delay)
|
||||
attempts--
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func GenerateTokenPair(id int) (map[string]string, error) {
|
||||
cfg := config.GetConfig()
|
||||
secret := []byte(cfg.JwtKey)
|
||||
|
||||
accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"id": id,
|
||||
"admin": true,
|
||||
"exp": time.Now().Add(time.Hour).Unix(),
|
||||
})
|
||||
|
||||
access, err := accessToken.SignedString(secret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
refreshToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"id": id,
|
||||
"exp": time.Now().Add(30 * 24 * time.Hour).Unix(),
|
||||
})
|
||||
|
||||
refresh, err := refreshToken.SignedString(secret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return map[string]string{
|
||||
"accessToken": access,
|
||||
"refreshToken": refresh,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func ParseRefreshToken(tokenString string) (jwt.MapClaims, error) {
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, jwt.ErrSignatureInvalid
|
||||
}
|
||||
return []byte(config.GetConfig().JwtKey), nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok || !token.Valid {
|
||||
return nil, jwt.ErrSignatureInvalid
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
func ClaimID(claims jwt.MapClaims) (int, bool) {
|
||||
id, ok := claims["id"].(float64)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
return int(id), true
|
||||
}
|
||||
Reference in New Issue
Block a user