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 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用