'Golang handlefunc with channel
I think this question has been asked before (and probably more than once) but I can't find it...
Im learning Go, and I wanted to extend the classical web server example by sending a channel to the "handler".
I have this standard thing:
func hello(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello world!")
}
func main() {
http.HandleFunc("/", hello)
http.ListenAndServe(":8000", nil)
}
And now I would like the "hello" function to be able to write stuff on a channel, for someone to consume... The way I have done with "normal" functions is to create a channel:
c := make(chan string)
and pass c in the call to the function. Something like:
dosomething(c)
But... how would I go about doing that if I want "hello" to get access to the channel c?
Solution 1:[1]
There a few ways to solve this problem, the simplest is to define an exported channel in a package and import said package where ever you want to use the channel.
package mychannel
var Chan = make(chan string)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jmaloney |
