Golang handlefunc 带通道

我认为这个问题以前曾被问过(可能不止一次),但我找不到它......


我正在学习 Go,我想通过向“处理程序”发送一个通道来扩展经典的 Web 服务器示例。


我有这个标准的东西:


func hello(w http.ResponseWriter, r *http.Request) {

   io.WriteString(w, "Hello world!")

}


func main() {

    http.HandleFunc("/", hello)

    http.ListenAndServe(":8000", nil)

}

现在我希望“hello”函数能够在频道上写东西,供某人消费......我对“普通”函数所做的方法是创建一个频道:


c := make(chan string) 

并在对函数的调用中传递 c。就像是:


dosomething(c)

但是......如果我想要“你好”访问频道c,我该怎么做?


撒科打诨
浏览 170回答 2
2回答

慕姐8265434

还有其他两种方法可以做到这一点(除了像上一个答案那样导出频道)。第一种是使用一个函数返回另一个处理函数。当函数返回时,它会在通道周围创建一个闭包。func makeHello(logger chan string) func(http.ResponseWriter, *http.Request) {&nbsp; &nbsp; return func(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; &nbsp; &nbsp; logger <- r.Host&nbsp; &nbsp; &nbsp; &nbsp; io.WriteString(w, "Hello world!")&nbsp; &nbsp; }}第二种是使用一个结构体,该结构体将通道作为成员保存,并使用指针接收器方法来处理请求......type DataPasser struct {&nbsp; &nbsp; logs chan string}func (p *DataPasser) handleHello(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; p.logs <- r.URL.String()&nbsp; &nbsp; io.WriteString(w, "Hello world")}这是一个完整的工作示例(只需点击 /1 和 /2 即可查看两个示例)package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "io"&nbsp; &nbsp; "net/http")func main() {&nbsp; &nbsp; // METHOD 1&nbsp; &nbsp; logs := make(chan string)&nbsp; &nbsp; go logLogs(logs)&nbsp; &nbsp; handleHello := makeHello(logs)&nbsp; &nbsp; // METHOD 2&nbsp; &nbsp; passer := &DataPasser{logs: make(chan string)}&nbsp; &nbsp; go passer.log()&nbsp; &nbsp; http.HandleFunc("/1", handleHello)&nbsp; &nbsp; http.HandleFunc("/2", passer.handleHello)&nbsp; &nbsp; http.ListenAndServe(":9999", nil)}// METHOD 1func makeHello(logger chan string) func(http.ResponseWriter, *http.Request) {&nbsp; &nbsp; return func(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; &nbsp; &nbsp; logger <- r.Host&nbsp; &nbsp; &nbsp; &nbsp; io.WriteString(w, "Hello world!")&nbsp; &nbsp; }}func logLogs(logger chan string) {&nbsp; &nbsp; for item := range logger {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("1. Item", item)&nbsp; &nbsp; }}// METHOD 2type DataPasser struct {&nbsp; &nbsp; logs chan string}func (p *DataPasser) handleHello(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; p.logs <- r.URL.String()&nbsp; &nbsp; io.WriteString(w, "Hello world")}func (p *DataPasser) log() {&nbsp; &nbsp; for item := range p.logs {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("2. Item", item)&nbsp; &nbsp; }}

慕姐4208626

有几种方法可以解决这个问题,最简单的方法是在一个包中定义一个导出的通道,然后在你想要使用该通道的任何地方导入该包。package mychannelvar Chan = make(chan string)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go