Skip to content

Instantly share code, notes, and snippets.

@monmohan
Last active July 11, 2020 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monmohan/6aeb1929b01faae3a459a94778256134 to your computer and use it in GitHub Desktop.
Save monmohan/6aeb1929b01faae3a459a94778256134 to your computer and use it in GitHub Desktop.
Sample code to accompany the blog
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/http/httputil"
"time"
"golang.org/x/net/context"
)
type ResponseHandler func(resp *http.Response, err error) error
func main() {
url := runTestServer() //just for testing
err := DoGetWithTimeout(url, stdOutHandler, time.Duration(6*time.Second))
if err != nil {
fmt.Printf("Error in GET request to server %s, error = %s", url, err)
}
}
//DoGetWithTimeout - Makes a request with context that timesput
func DoGetWithTimeout(getURL string, respHandler ResponseHandler, timeout time.Duration) error {
ctx, cancelFunc := context.WithTimeout(context.Background(), timeout)
defer cancelFunc()
request, _ := http.NewRequestWithContext(ctx, "GET", getURL, nil)
fResult := make(chan error, 0)
go func() {
fResult <- RoundTrip(request, respHandler)
}()
select {
case <-ctx.Done():
<-fResult //let the go routine end too
return ctx.Err()
case err := <-fResult:
return err //any other errors in response
}
}
//RoundTrip makes an http request and processes the response through a Response Handler func
func RoundTrip(request *http.Request, respHandler ResponseHandler) error {
return respHandler(http.DefaultClient.Do(request))
}
func stdOutHandler(resp *http.Response, err error) error {
if err != nil {
return err
}
defer resp.Body.Close()
//Handle the response
//In this case we just print the body
body, _ := ioutil.ReadAll(resp.Body)
fmt.Printf("Body from response %s\n", string(body))
return nil
}
func runTestServer() string {
slowServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
incoming, _ := httputil.DumpRequest(r, false)
fmt.Printf("Server: Incoming Request %s", string(incoming))
time.Sleep(10 * time.Second) // Do difficult Job
w.Write([]byte("Hello There!"))
}))
return slowServer.URL
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment