我在appengine中发出HTTP请求时遇到了问题,因为它不支持http.Client。我正在创建一个slackbot,并且想创建一个延迟响应。逻辑是,一旦我收到slack的POST请求,我将成功响应并旋转一个调用外部API的goroutine,在我完成它之后,创建一个新的请求来slack。
看起来很简单,但我遇到的问题是在使用appengine的urlfetch和NewContext时,因为NewContext接受*http.Request作为参数,但由于我立即响应第一个松弛请求,响应主体在我可以使用它向外部API发出响应之前就关闭了。有没有别的选择?
代码:
func Twit(w http.ResponseWriter, r *http.Request) {
defaultResponse := &SlashResponse{ResponseType: "ephemeral", Text: "success"}
// prepare to make a slack delayed response
responseURL := r.FormValue("response_url")
go sendDelayResponse(responseURL, r)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
json.NewEncoder(w).Encode(defaultResponse)
}
func sendDelayResponse(url string, r *http.Request) {
response := &SlashResponse{ResponseType: "in_channel", Text: twit.TweetTCL(r)}
b, _ := json.Marshal(response)
// send request to slack using given response_url
ctx := appengine.NewContext(r)
client := urlfetch.Client(ctx)
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(b))
req.Header.Add("Content-Type", "application/json")
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
log.Println(err)
} else {
log.Println("success")
}
}发布于 2017-01-23 23:20:10
使用delay包执行请求范围之外的函数。
您还可以使用较低级别的taskqueue包。延迟包位于taskqueue包之上。
使用delay函数声明包级变量:
var laterFunc("dr", func(ctx context.Context, url string) {
response := &SlashResponse{ResponseType: "in_channel", Text: twit.TweetTCL(r)}
b, _ := json.Marshal(response)
// send request to slack using given response_url
client := urlfetch.Client(ctx)
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(b))
req.Header.Add("Content-Type", "application/json")
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
log.Println(err)
} else {
log.Println("success")
}
})这样叫它:
laterfunc.Call(appengine.NewContext(r), responseURL)https://stackoverflow.com/questions/41796830
复制相似问题