Skip to content

Iter26 - #26

Merged
anon-d merged 4 commits into
mainfrom
iter26
Apr 20, 2026
Merged

anon-d merged 4 commits into
mainfrom
iter26

Conversation

@anon-d

@anon-d anon-d commented Apr 13, 2026

Copy link
Copy Markdown
Owner

added graceful shutdown

Comment thread cmd/certificate/main.go Outdated
// создаём сертификат x.509
certBytes, err := x509.CreateCertificate(rand.Reader, cert, cert, &privateKey.PublicKey, privateKey)
if err != nil {
log.Fatal(err)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

К каждой подобной ошибке стоит добавить информацию о том, что именно пошло не так:

Suggested change
log.Fatal(err)
log.Fatalf("failed to create a certificate: %v", err)

Comment thread cmd/shortener/main.go Outdated

out := make(chan os.Signal, 1)
signal.Notify(out, syscall.SIGINT, syscall.SIGTERM)
signal.Notify(out, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Для реализации graceful shutdown правильнее использовать https://pkg.go.dev/os/signal#NotifyContext: это позволяет получать сигнал о завершении программы не по каналу, а через контекст, что более идиоматично

Comment thread internal/app/app.go Outdated
// Run запускает HTTP-сервер.
func (a *App) Run() error {
if a.enableTLS {
return a.server.ListenAndServeTLS("cert.pem", "key.pem")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Не хардкодь пути к файлам сертификата, лучше сделай их конфигурируемыми

Comment thread internal/config/flag/config.go Outdated

cfg := &ServerConfig{}
// Определяем, какие флаги были явно переданы
flagSet := make(map[string]bool)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Твое решение, в принципе, жизнеспособно. На реальных проектах для получения конфигурации из разных источников обычно используется один из следующих подходов:

  • использование пакета https://github.com/spf13/viper: с его помощью можно удобно считывать конфигуарцию из флагов, переменных окружения и файла одновременно
  • создание трех объектов конфигурации -- из флагов, из переменных окружения и из файла -- и их слияние при помощи например, пакета, https://github.com/darccio/mergo

Первый способ встречается чаще. Кроме того на реальных пректах зачастую кофнигурации получается только одним каким-то способом (через переменные оркужения, например), но это не касается учебного проекта.

Если будешь чувствовать в себе силы, то используй один из описанных подходов

Comment thread internal/config/flag/config.go Outdated
cfg.AddrServer = envAddr
} else {
// Загружаем JSON-конфиг, если путь задан
var jcfg *JSONFileConfig

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Если сервис может использовать получать конфигурацию через файл, то хорошей практикой будет добавить в репозиторий config.example.json, чтобы было понятно, какие параметры можно в нем определить. Естественно, там должны быть только дефолтные значения параметров

- fix(core): added description in error exception;

- feat(config): added Viper config creator;

- feat(etc): added example config file;
@anon-d
anon-d merged commit ddab361 into main Apr 20, 2026
3 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.

2 participants