Sobes.tech
Middle+

Live coding: add a timeout to a function — if execution exceeds 1 second, return an error. Use select, time.After, context.

sobes.tech AI

Answer from AI

To add a timeout to a function in Go, you can use a select statement with time.After. You can also use context.WithTimeout for more flexible timeout management.

Example with select and time.After:

package main

import (
    "errors"
    "fmt"
    "time"
)

func doWork() error {
    // Simulate long-running work
    time.Sleep(2 * time.Second)
    return nil
}

func doWorkWithTimeout() error {
    done := make(chan error, 1)
    go func() {
        done <- doWork()
    }()

    select {
    case err := <-done:
        return err
    case <-time.After(1 * time.Second):
        return errors.New("timeout: execution exceeded 1 second")
    }
}

func main() {
    err := doWorkWithTimeout()
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("Success")
    }
}

Example using context.WithTimeout:

package main

import (
    "context"
    "errors"
    "fmt"
    "time"
)

func doWork(ctx context.Context) error {
    select {
    case <-time.After(2 * time.Second):
        return nil
    case <-ctx.Done():
        return ctx.Err()
    }
}

func doWorkWithTimeout() error {
    ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
    defer cancel()

    err := doWork(ctx)
    if err != nil {
        if errors.Is(err, context.DeadlineExceeded) {
            return errors.New("timeout: execution exceeded 1 second")
        }
        return err
    }
    return nil
}

func main() {
    err := doWorkWithTimeout()
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("Success")
    }
}

Both options allow you to cancel the function execution if it takes longer than 1 second.

Live coding: add a timeout to a function — if… - sobes.tech