2018-08-06 01:07
浏览 141


If I use a chan anywhere on main or func home, the application runs, but it doesn't really work. No errors thrown, however, it won't work. If I remove the channels references, it goes back to working. Either by using a chan in a struct or a global channel the application stops working.

In a GET request, it returns h.Message from func home by adding any channel in the code, GET request wont return the message.

package main

import (

    // _ ""

type WMessage struct {
    Message string `json:"message"`
    ch      chan string

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
    CheckOrigin: func(r *http.Request) bool {
        return true

var Chann chan string

func (h *WMessage) home(w http.ResponseWriter, r *http.Request) {
    h.Message = "hey this is the message from home"

    fmt.Fprintln(w, h.Message)

func main() {
    hom := &WMessage{} = make(chan string) <- "message sent"

    http.HandleFunc("/", hom.home)
    err := http.ListenAndServe(":3000", nil)
    if err != nil {
        fmt.Println("there was an error -> ", err)
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douduiti3040 2018-08-06 04:11

    Unbuffered channels are blocking in nature, i.e. writing to channel ( <- "message sent") and reading from channel (fmt.Println(< block the go-routine.

    In your case, http server is not running because <- "message sent" blocks the execution. That's why GET request is not working.

    One simple solution can be to make it buffered channel instead.

    打赏 评论

相关推荐 更多相似问题