min2bro
min2bro

Reputation: 4638

Return response from a Handler Func

I am fairly new to golang and in one of the handler functions I'm collecting the data using channels from different goroutines and now wanted to return the array of result as a response object

So I have given a return type as the struct details but it's throwing an error

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

Error:

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

Handler Func:

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



}

Upvotes: 0

Views: 6554

Answers (1)

Mikey
Mikey

Reputation: 2704

So, your question is two fold. Firstly the reason for the error is because if you look at the documentation here you can see that http.HandleFunc has the following definition.

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

Since your function has a return with []details it does not meet the requirements.

So going off the other part of your question;

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

To solve your problem we need to write your data back to the response, you'll notice in the arguments passed to your HandleFunc you have a ResponseWriter, where you can use the Write() method to return your response

Not entirely sure how you want to display your result but you could do it with JSON easy enough.

b, err := json.Marshal(results)
if err != nil {
    // Handle Error
}
w.Write(b)

Upvotes: 7

Related Questions