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 h3.6m 人类行为预测论文复现
  • ¥50 wordpress项目注册报失败刷新后其实是成功状态,请求排查原因
  • ¥20 linxu服务器僵尸进程不释放,代码如何修改?
  • ¥15 pycharm激活不成功
  • ¥40 如果update 一个列名为参数的value
  • ¥15 基于51单片机的水位检测系统设计中LCD1602一直不显示
  • ¥15 OCS2安装出现问题,请大家给点意见
  • ¥15 ros小车启动launch文件报错
  • ¥15 vs2015到期想登陆但是登陆不上
  • ¥15 IPQ5018制作烧录固件,boot运行失败(操作系统-linux)(相关搜索:操作系统)(相关搜索:操作系统)