Skip to content

Instantly share code, notes, and snippets.

@sayden
Created August 17, 2018 22:04
Show Gist options
  • Save sayden/e158a3080fb1ff66ee321e1c3857233d to your computer and use it in GitHub Desktop.
Save sayden/e158a3080fb1ff66ee321e1c3857233d to your computer and use it in GitHub Desktop.
package main
import (
"context"
"encoding/json"
"github.com/juju/errors"
"github.com/thehivecorporation/log"
"net/http"
"time"
)
type res struct {
Success bool
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
err := potentiallySlowOperation(r.Context(), 5)
if err != nil {
log.WithError(err).Error("Error while 'processing'")
w.WriteHeader(500)
return
}
byt, err := json.Marshal(res{Success: true})
if err != nil {
w.WriteHeader(500)
return
}
w.Write(byt)
})
http.ListenAndServe(":8080", nil)
}
func potentiallySlowOperation(ctx context.Context, s time.Duration) error {
log.Infof("'Processing' for %d seconds", s)
now := time.Now()
defer func(now time.Time) {
log.WithField("elapsed", time.Since(now)).Info("Returning")
}(now)
select {
case <-time.After(time.Second * s):
log.Info("Processing done")
case <-ctx.Done():
return errors.New("Context cancelled")
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment