package context_handler import ( "context" "errors" "fmt" "time" ) type keyType string const userKey keyType = "userID" // WithUserID stores user id in context func WithUserID(ctx context.Context, userID string) context.Context { return context.WithValue(ctx, userKey, userID) } // FetchRiwayatKursus simulates fetching course history but respects context deadlines/cancel. func FetchRiwayatKursus(ctx context.Context) (string, error) { // try to read user ID uid, _ := ctx.Value(userKey).(string) if uid == "" { uid = "unknown" } // simulate work that may take up to 2 seconds work := make(chan string, 1) go func() { // simulate slower work 1.5s time.Sleep(1500 * time.Millisecond) work <- fmt.Sprintf("history for user %s: [Course-A, Course-B]", uid) }() select { case <-ctx.Done(): // context timed out or cancelled return "", errors.New("fetch cancelled or timed out: " + ctx.Err().Error()) case res := <-work: return res, nil } }