【发布时间】:2018-09-11 05:24:32
【问题描述】:
我有一个函数,它可能会或可能不会被称为异步 go-routine。
func APICall(request *HTTPRequest) *HTTPResponse
*HTTPRequest 是一个指向结构的指针,该结构包含构建请求所需的各种数据:
type HTTPRequest struct {
// Represents a request to the twitter API
method string
baseurl string
urlParams map[string]string
bodyParams map[string]string
authParams map[string]string
responseChan chan *HTTPResponse
}
如果作为 goroutine 调用,即传入一个通道;我们构建请求并将响应写入所提供通道的 *HTTPResponse 对象(也是一个结构)。在没有通道的情况下接受对函数的调用的最优雅/惯用的方式是什么(即非异步)
目前,我们在 APICall 的主体中做这样的事情来处理这两种函数调用:
if request.responseChan != nil { // If a response channel has been specified, write to that channel
request.responseChan <- &twitterHTTPResponse{body, nil}
return nil // Not returning a struct
} else {
return &twitterHTTPResponse{body, nil} // Return a pointer to a new struct representing the response
}
我们的路线正确吗?
【问题讨论】:
-
惯用的方法是编写同步 API 并留给调用者执行来自 goroutine 的调用。
-
如何解决是否需要通道的歧义?
-
同步 API 不使用通道。惯用的方法是从
HTTPRequest中删除responeChan,然后简单地从函数中返回&twitterHTTPResponse{body, nil}, err。
标签: asynchronous go goroutine