Created
May 25, 2018 02:47
-
-
Save sinmetal/d3c7b1c027ce04bbf54967fa895ea096 to your computer and use it in GitHub Desktop.
urlfetch context.WithTimeout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"net/http" | |
"time" | |
"google.golang.org/appengine" | |
"google.golang.org/appengine/urlfetch" | |
) | |
func init() { | |
http.HandleFunc("/hello", handler) | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
ctx := appengine.NewContext(r) | |
status, err := getHoge(ctx) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
fmt.Fprintf(w, "%s", status) | |
} | |
func getHoge(ctx context.Context) (string, error) { | |
cctx, cancel := context.WithTimeout(ctx, 30*time.Second) | |
defer cancel() | |
uf := urlfetch.Client(cctx) | |
req, err := http.NewRequest(http.MethodGet, "https://google.com", nil) | |
if err != nil { | |
return "", err | |
} | |
res, err := uf.Do(req) | |
if err != nil { | |
return "", err | |
} | |
return res.Status, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment