Skip to content

Instantly share code, notes, and snippets.

@jlindsey
Created December 8, 2016 20:08
Show Gist options
  • Save jlindsey/300fa751de7f9b9af08a6fa35c390898 to your computer and use it in GitHub Desktop.
Save jlindsey/300fa751de7f9b9af08a6fa35c390898 to your computer and use it in GitHub Desktop.
func (db *DB) loadEvent(ctx context.Context, id int) (event, error) {
timeoutCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
logger := timeoutCtx.Value("logger").(ILogger)
outChan := make(chan event)
errChan := make(chan error)
go func() {
ev := event{}
err := db.conn.QueryRow(db.queries["event_by_id"], id).Scan(&ev.ownerID)
switch {
case err == sql.ErrNoRows:
errChan <- fmt.Errorf("No event found with id %d", id)
case err != nil:
errChan <- err
default:
logger.Debug("Event for id %d: %v", id, ev)
outChan <- ev
}
}()
select {
case ev := <-outChan:
return ev, nil
case err := <-errChan:
return event{}, err
case <-timeoutCtx.Done():
return event{}, fmt.Errorf("context timeout: %v", timeoutCtx.Err())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment