Go attempts to fetch values from channel in Goroutine for HTTP response

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Recently, a small partner has asked the following questions.

Handler gets a request, and then puts the request into a channel, and a gorutine always takes the value from the channel to do the processing. If I want to return the results in handler, is the current process not possible?


He asked me that because he was a vegetable chicken and could not answer, I intend to try it myself.

First, a few simple HTTP servers

func main(){http.HandleFunc("/", handler)http.ListenAndServe("localhost:8082", nil)}

Then run the Goroutine and the channel.

func Test (){ch := make(chan int, 1)sign := make(chan byte, 2)go func() {for i := 0; i < 5; i++ {ch <- itime.Sleep(1 * time.Second)}close(ch)fmt.Println("The channel is closed.")sign <- 0}()go func() {//这个循环会一直尝试从ch中读取信息出来 即使ch已经被发送端关闭//但还是可以读信息出来 最后当ok 为false的时候 说明已经没有数据从ch中读出//跳出循环 注意这种判断方式for {fmt.Printf("before extract channel len: %v ,", len(ch))e, ok := <-chfmt.Printf("channel value: %d if extract ok :(%v) after extraction channel len : %v channel cap : %v \n", e, ok, len(ch), cap(ch))if !ok {break}time.Sleep(2 * time.Second)}fmt.Println("Done.")sign <- 1}()//要是不添加两次取值的操作的话 主进程就会马上结束 这里相当于是实现了一个//同步的操作 等待两个go func都结束之后 再结束主进程 注意这种技巧<-sign<-sign}

Basically no problem, then the code was modified, and then got the following code

Structural body

type HandlerDemo struct {writer  http.ResponseWriterrequest *http.Request}

Specific implementation code

 func Handler (w http. Responsewriter, R *http. Request) {fmt. Println ("Start ...")//test Response/*w.writeheader (http. Statusok)//200FMT. fprintf (W, "This msg:%v\n", 123) Return*/info:=handlerdemo{}info.writer=winfo.request=rresult:=handlerdemo{}ch: = Make (Chan Handlerdemo, 1) ch <-infoclose (CH) fmt. PRINTLN ("CH is has data...") Go func () {fmt. Println ("Start run Goroutine.") Fmt. Println ("Try Get ch val ...") E, OK: = <-chfmt. PRINTF ("Channel value:%d If extract OK:(%v) after extraction channel Len:%V channel Cap:%v \ n", E, OK, Len (ch), Cap ( CH)) If ok{result.writer=e.writerresult.request=e.requestfmt.printf ("result value:%d \ n", Result)}} () time. Sleep (3 * time. Second) fmt. Println ("Over ...") fmt. Println ("This Val is get and try response ...") Result.writer.WriteHeader (http. Statusok) fmt. fprintf (Result.writer, "This response msg:%v\n", "Hello") return}  

As you can see, I've been stuck with sleep for a long time before returning the information successfully. The HTTP input must output, when the Goroutine is the equivalent of asynchronous, communication will continue until the end, it will first return null value, return in the Goroutine will be returned several times, so I used the extreme method to return, got the long-lost hello. But this method obviously is not suitable for the application, the improvement method changes the sleep time to judge Goroutine end , this is more reasonable!! Ha ha haha

314 reads ∙1 likes
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.