如何让Node.js与Golang进行通信

7

我正在使用node.js和golang创建一个web应用程序。我需要连接nodejs和golang代码,该代码与mongodb通信并将数据返回给node程序。有没有办法连接它们?我尝试使用gonode API。这是使用gonode API的代码。

我的node.js文件包含以下代码:

var Go = require('gonode').Go;
var options = {
path : 'gofile.go',
initAtOnce : true,
}

var go = new Go(options,function(err){
if(err) throw err;

go.execute({commandText: 'Hello world from gonode!'}, function(result, response) {
        if(result.ok) {
            console.log('Go responded: ' + response.responseText);
        }
});

go.close();
});     `

这是我在gofile.go文件中的代码:

package main

import(
    gonode "github.com/jgranstrom/gonodepkg"
    json "github.com/jgranstrom/go-simplejson"
)

func main(){
    gonode.Start(process)
}

func process(cmd *json.Json) (response *json.Json) {    
    response, m := json.MakeMap()

    if(cmd.Get("commandText").MustString() == "Hello") {
        m["responseText"] = "Well hello there!"
    } else {
        m["responseText"] = "What?"
    }

    return
}

在终端中运行node.js时,我遇到了以下错误:


events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: write EPIPE
    at errnoException (net.js:905:11)
    at Object.afterWrite (net.js:721:19)
3个回答

7

5
感谢您的回复。我已经找到了解决方案。我建立了两个不同的服务器,一个是用NodeJS实现的,另一个是用Golang实现的。在Node服务器中调用Golang URI,并从Golang服务器获取数据。

0

基于对gonode源代码的非常粗略的检查,该模块似乎会生成go代码作为子进程,并通过stdin/-out进行通信。EPIPE错误意味着另一端关闭了流。基于此,可能是您的go进程过早退出。

您可以尝试通过修改gonode/lib/command.js中的Command.prototype.execute来打印发送到go进程的JSON,以调试问题。然后,您可以直接运行它并通过stdin提供相同的输入来调试go程序。


此外,Go 代码示例似乎与您的代码有所不同。在函数开头,它调用 response = make(gonode.CommandData),并且在 if 语句中,response 被分配为:response["text"] = "What?"。虽然我对 Go 不是很了解,但似乎您的变量 m 并没有真正连接到任何东西。https://www.npmjs.com/package/gonode - Juho

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接