douhu7807 2019-08-18 21:40
浏览 27
已采纳

Web服务器和同时收听内容

My code reads input from terminal and send those value to nats while it needs to have an http endpoint.

Separately it works but when I combine all of them it does not read from nats. If you could point me to a right direction I would appreciate.

package main

import (
    "bufio"
    "fmt"
    nats "github.com/nats-io/nats.go"
    "html/template"
    "log"
    "net/http"
    "os"
)


func main() {
    wd, err := os.Getwd()
    if err != nil {
        log.Fatal(err)
    }

    tmpl := template.Must(template.ParseFiles(wd + "/template/main.html"))
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        data := TodoPageData{
            PageTitle: "Demo",          
        }
        tmpl.Execute(w, data)
    })
    http.ListenAndServe(":8081", nil)

    type message struct {
        content string
    }
    var messages []message

    nc, err := nats.Connect(
        nats.DefaultURL,
    )

    if err != nil {
        log.Fatal(err)
    }
    defer nc.Close()

    // Subscribe
    if _, err := nc.Subscribe("updates", func(m *nats.Msg) {
        fmt.Printf("Received a message: %s
", string(m.Data))
    }); err != nil {
        log.Fatal(err)
    }

    // io r/w
    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        if err := nc.Publish("updates", []byte(scanner.Text())); err != nil {
            log.Fatal(err)
        }
        messages = append(messages, message{scanner.Text()})
        for _, message := range messages {
            fmt.Println(message.content)
        }
    }

    if scanner.Err() != nil {
        // handle error.
    }
}
  • 写回答

1条回答 默认 最新

  • dongwalun2507 2019-08-18 21:50
    关注

    http.ListenAndServe is a blocking call. Start it on a new goroutine:

    go http.ListenAndServe(":8081", nil)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献