go - 从处理程序函数返回响应

标签 go goroutine

我对golang相当陌生,在其中一个处理函数中,我正在使用来自不同goroutines的 channel 收集数据,现在想返回结果数组作为响应对象

所以我给了一个返回类型作为结构细节,但是它抛出一个错误

如果这不是将结构片作为响应返回的方式,那么我如何返回结果数组作为响应以发布我的请求

错误:

cannot use homePage (type func(http.ResponseWriter, *http.Request) []details) as type func(http.ResponseWriter, *http.Request) in argument to http.HandleFunc

处理函数:
func homePage(w http.ResponseWriter, r *http.Request) []details{    

    var wg sync.WaitGroup    


    for _, url := range urls {  
        out, err := json.Marshal(url)
        if err != nil {
            panic (err)
        }        
        wg.Add(1)
        go do_calc(ch,client,string(out),&wg)        
    }

    fmt.Println("Returning Response")  
    go func() {
        for v := range ch {
            results = append(results, v)
        }
    }()
    wg.Wait()
    close(ch)  

    return results



}

最佳答案

因此,您的问题有两个。首先,导致错误的原因是因为如果您查看here文档,您会看到http.HandleFunc具有以下定义。

func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

由于您的函数使用[]details返回,因此它不符合要求。

因此,从问题的另一部分出发;

if this is not the way to return the slice of struct as response then how can I return my results array as a response to post my request



为了解决您的问题,我们需要将数据写回到响应中,您会注意到在传递给HandleFunc的参数中您有一个ResponseWriter,您可以在其中使用Write()方法返回响应

不确定要如何显示结果,但可以使用JSON轻松完成。
b, err := json.Marshal(results)
if err != nil {
    // Handle Error
}
w.Write(b)

关于go - 从处理程序函数返回响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60035928/

相关文章:

json - 在 App Engine 中将 *bytes.Buffer 转换为 json 和 Unmarshal

go - Go 结构字段的第三个参数是什么?

go - 基准 Go 代码和 goroutines

go - 如何等待 goroutines 完成并在没有锁的情况下读取 channel ?

Go, Golang : array type inside struct, 缺少类型复合文字

function - 如何将 time.Duration 类型传递给 go 函数?

go - gitlab-ci无法将golang构建的二进制文件上传到nexus

go - 带有sync.waitGroup的Goroutine每次输出不同的值

go - 尝试从永远不会在goroutine中接收数据但在主func中接收数据的 channel 读取时,为什么没有死锁

go - 如何优雅地关闭 golang 服务器?