Context & select

Базовая работа с context и выбором select в Golang.

package main
 
import (
	"context"
	"time"
 
	"github.com/juju/zaputil/zapctx"
	"go.uber.org/zap"
)
 
type key struct{}
 
func doWork(ctx context.Context) {
	logger := zapctx.Logger(ctx)
 
	logger.Info(ctx.Value(key{}).(string))
	for {
		select {
		case <-ctx.Done():
			logger.Info("ctx canceled")
			return
		default:
			logger.Info("Working")
			time.Sleep(time.Second)
		}
	}
}
 
func main() {
	ctx := context.Background()
 
	logger, _ := zap.NewProduction()
	logger = logger.With(zap.String("env", "prod"))
 
	logger.Info("Start app")
 
	logCtx := zapctx.WithLogger(ctx, logger)
	ctxLogWithValue := context.WithValue(logCtx, key{}, "iddqd")
 
	ctxTimeout, _ := context.WithTimeout(ctxLogWithValue, time.Second*5)
	doWork(ctxTimeout)
 
	ctxCancel, cancel := context.WithCancel(ctxLogWithValue)
	go doWork(ctxCancel)
	time.Sleep(time.Second * 6)
	cancel()
}