Skip to content

Instantly share code, notes, and snippets.

@sayden
Created August 17, 2018 22:06
Show Gist options
  • Save sayden/413b9bd66b27807abb16864f93484b93 to your computer and use it in GitHub Desktop.
Save sayden/413b9bd66b27807abb16864f93484b93 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
Err string
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
var response res
err := potentiallySlowOperation(r.Context(), 5)
if err != nil {
log.WithError(err).Error("Error while 'processing'")
response = res{Success: false, Err: err.Error()}
} else {
response = res{Success: true}
}
byt, err := json.Marshal(response)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if !response.Success {
w.WriteHeader(http.StatusInternalServerError)
}
w.Write(byt)
})
http.ListenAndServe(":8080", nil)
}
var slow = false
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)
var waitingTimeCh <-chan time.Time
if slow {
waitingTimeCh = time.After(time.Minute * 5 * 60)
slow = false
} else {
waitingTimeCh = time.After(time.Second * s)
slow = true
}
newCtx, cancelFun := context.WithTimeout(ctx, time.Second*6)
defer cancelFun()
select {
case <-waitingTimeCh:
log.Info("Processing done")
case <-newCtx.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