Skip to content

Conversation

@DEMAxx
Copy link
Owner

@DEMAxx DEMAxx commented Mar 31, 2025

Домашнее задание №12 «Заготовка сервиса Календарь»

Критерии оценки

  • Makefile заполнен и пайплайн зеленый - 1 балл
  • Понятность и чистота кода (включая факт, что проект разбит
    на пакеты по определенной логике) - до 2 баллов
  • Реализовано конфигурирование сервиса - 1 балл
  • Используется логгер и он настраивается из конфига - 1 балл
  • Запускается простой HTTP-сервер, мидлвара удовлетворяет ТЗ - 1 балл
  • Присутствуют юнит-тесты - 1 балл

Реализовано хранилище:

  • in-memory - 1 балл
  • sql + миграции - 2 балла

Зачёт от 7 баллов

Copy link

@agneum agneum left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Спасибо за вариант решения. Хорошая работа
Итого: 8 баллов из 10. Принято

Comment on lines +39 to +46
switch conf.Logger.Output {
case "stderr":
logg = logg.Output(os.Stderr)
case "stdout":
logg = logg.Output(os.Stdout)
default:
logg = logg.Output(os.Stdout) // Default to stdout if not specified
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Конфигурацию логгера лучше сделать в конструкторе и не выносить в main

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

logg := logger.New(ctx, conf.Logger.Level, nil, true)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Предложил бы использовать структуру для передачи параметров в конструктор. nil и bool в качестве аргументов выглядят не очень хорошо

Comment on lines +49 to +57
for {
conn, err := listener.Accept()
if err != nil {
log.Printf("failed to accept connection: %v", err)
continue
}

go handleConnection(conn)
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не совсем понимаю, для чего этот цикл

Port: conf.DB.Port,
Name: conf.DB.Name,
}); err != nil {
panic(err)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Желательно не паниковать и корреткно обработать ошибку

@@ -0,0 +1,67 @@
package main
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Предложил бы использовать бинарник goose, т.к. приложение, использующее его пакеты, не добавляет специальной функциональностью. Скорее, наоборот, его функциональность ограничена

@@ -0,0 +1,123 @@
package envreader
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Для конфигурации приложения рекомендовал бы использовать один файл в удобном формате и любой парсер этого файла, либо специальный пакет для загрузки конфигурации

Comment on lines +33 to +45
clientIP := r.RemoteAddr
dateTime := time.Now().Format(time.RFC3339)
method := r.Method
path := r.URL.Path
httpVersion := r.Proto
userAgent := r.Header.Get("User-Agent")

logger.Info(
fmt.Sprintf(
"Client IP: %s, DateTime: %s, Method: %s, Path: %s, HTTP Version: %s, User Agent: %s",
clientIP, dateTime, method, path, httpVersion, userAgent,
),
)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кажется, дублируется код middleware

Comment on lines +37 to +41
select {
case <-ctx.Done():
return ctx.Err()
default:
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В in-memory хранилище все операции достаточно быстрые, нет взаимодействия со сторонними сервисами и т.д., поэтому использование контекста не имеет существенной роли

Comment on lines +76 to +106
func New(ctx context.Context, level string, sampler Sampler, stack bool) *Logger {
var logs Logger
logs.ctx = ctx
logs.sampler = sampler
logs.stack = stack

switch level {
case "trace":
logs.Level(TraceLevel)
case "debug":
logs = logs.Level(DebugLevel)
case "warn":
logs = logs.Level(WarnLevel)
case "error":
logs = logs.Level(ErrorLevel)
default:
logs = logs.Level(InfoLevel)
}

return &logs
}

func NewWriter(ctx context.Context, w io.Writer, sampler Sampler, stack bool) Logger {
if w == nil {
w = io.Discard
}
lw, ok := w.(LevelWriter)
if !ok {
lw = LevelWriterAdapter{w}
}
return Logger{w: lw, level: TraceLevel, ctx: ctx, sampler: sampler, stack: stack}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Два конструктора с разным набором аргументов выглядят необычно.

@@ -1,20 +1,148 @@
package logger
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Предложил бы использовать стандартный пакет для логирования https://pkg.go.dev/log

@DEMAxx DEMAxx merged commit 1969cce into master Apr 8, 2025
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants