Skip to content

Commit

Permalink
ud
Browse files Browse the repository at this point in the history
  • Loading branch information
skantay committed Apr 16, 2024
1 parent b7bb31c commit 4e599b2
Show file tree
Hide file tree
Showing 4 changed files with 117 additions and 7 deletions.
25 changes: 25 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package config

import (
"fmt"

"github.com/spf13/viper"
)

type Config struct{}

func New(path string) (Config, error) {
viper.SetConfigFile(path)

var config Config

if err := viper.ReadInConfig(); err != nil {
return config, fmt.Errorf("failed to read config: %w", err)
}

if err := viper.Unmarshal(&config); err != nil {
return config, fmt.Errorf("failed to unmarshal config: %w", err)
}

return config, nil
}
32 changes: 32 additions & 0 deletions pkg/httpserver/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package httpserver

import (
"net"
"time"
)

type Option func(*Server)

func Port(port string) Option {
return func(s *Server) {
s.server.Addr = net.JoinHostPort("", port)
}
}

func ReadTimeout(timeout time.Duration) Option {
return func(s *Server) {
s.server.ReadTimeout = timeout
}
}

func WriteTimeout(timeout time.Duration) Option {
return func(s *Server) {
s.server.WriteTimeout = timeout
}
}

func ShutdownTimeout(timeout time.Duration) Option {
return func(s *Server) {
s.shutdownTimeout = timeout
}
}
36 changes: 29 additions & 7 deletions pkg/httpserver/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,54 @@ import (
"time"
)

// Значения по умолчнию для сервера
const (
defaultReadTimeout = 5 * time.Second
defaultWriteTimeout = 5 * time.Second
defaultAddr = ":8000"
defaultShutdownTimeout = 3 * time.Second
)

// Структура сервера, где также реализуется gracfull shutdown
type Server struct {
server *http.Server
notify chan error
shutdownTimeout time.Duration
}

func New(handler http.Handler, timeout map[string]time.Duration, addr string) *Server {
// Конструктор принимающий http.Handler и options
// где options означает что пользователь задаёт свои настройки для сервера
// Например: меняет read timeout на 10 секунд когда как по умолчанию настроено 5 секунд
// Config pattern
func New(handler http.Handler, opts ...Option) *Server {

// Содаём http.Server где указываем значения по умолчанию
httpServer := &http.Server{
Handler: handler,
ReadTimeout: timeout["ReadTimeout"],
WriteTimeout: timeout["WriteTimeout"],
IdleTimeout: timeout["IdleTimeout"],
Addr: addr,
ReadTimeout: defaultReadTimeout,
WriteTimeout: defaultWriteTimeout,
Addr: defaultAddr,
}

// Создаём свою структуру где имплементируется gracful shutdown
s := &Server{
server: httpServer,
notify: make(chan error, 1),
shutdownTimeout: timeout["shutdownTimeout"],
shutdownTimeout: defaultShutdownTimeout,
}

// Тут применяютися пользовательские настройки на сервер
for _, opt := range opts {
opt(s)
}

// Запускаем наш сервер, операция не блокнируящая
s.start()

return s
}


func (s *Server) start() {
go func() {
s.notify <- s.server.ListenAndServe()
Expand All @@ -48,4 +70,4 @@ func (s *Server) Shutdown() error {
defer cancel()

return s.server.Shutdown(ctx)
}
}
31 changes: 31 additions & 0 deletions pkg/mongodb/mongodb.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package mongodb

import (
"context"
"fmt"
"time"

"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

const (
DefaultTimeout = 5 * time.Second
)

// Конструктор устанавливает связь с mongodb
func Connect(ctx context.Context, options *options.ClientOptions) (*mongo.Client, error) {
client, err := mongo.Connect(ctx, options)
if err != nil {
return nil, fmt.Errorf("failed to connect to mongodb: %w", err)
}

ctxTimeout, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()

if err := client.Ping(ctxTimeout, nil); err != nil {
return nil, fmt.Errorf("failed to ping db: %w", err)
}

return client, nil
}

0 comments on commit 4e599b2

Please sign in to comment.