I am trying to understand Context by reading https://blog.golang.org/context

the code in https://blog.golang.org/context/google/google.go uses transport.
CancelRequest

Since http.Request now (I am using go 1.7.3) has context support now,
I think the code can be simpler now. This is my version of Search:

https://play.golang.org/p/EaHrbogwM9
// Search sends query to Google search and returns the results. func 
Search(ctx context.Context, query string) (Results, error) { // Prepare the 
Google Search API request. req, err := http.NewRequest("GET", 
"https://ajax.googleapis.com/ajax/services/search/web?v=1.0";, nil) if err 
!= nil { return nil, err } q := req.URL.Query() q.Set("q", query) // If ctx 
is carrying the user IP address, forward it to the server. // Google APIs 
use the user IP to distinguish server-initiated requests // from end-user 
requests. if userIP, ok := userip.FromContext(ctx); ok { q.Set("userip", 
userIP.String()) } req.URL.RawQuery = q.Encode() // Issue the HTTP request 
and handle the response. The httpDo function // cancels the request if 
ctx.Done is closed. var results Results client := &http.Client{} req = 
req.WithContext(ctx) resp, err := client.Do(req) if err != nil { return 
nil, err } defer resp.Body.Close() // Parse the JSON search result. // 
https://developers.google.com/web-search/docs/#fonje var data struct { 
ResponseData struct { Results []struct { TitleNoFormatting string URL 
string } } } if err := json.NewDecoder(resp.Body).Decode(&data); err != nil 
{ return nil, err } for _, res := range data.ResponseData.Results { results 
= append(results, Result{Title: res.TitleNoFormatting, URL: res.URL}) } 
return results, nil } 

But it does not work correctly, first search after `go run server.go`

curl 'http://localhost:8080/search?q=golang&timeout=1s'


will give `context deadline exceeded`


but  after that repeated searches  will not return context deadline.

what's wrong?

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to