2015-06-20 123 views
2

我在node.js和golang中創建了一個web應用程序。我需要將nodejs與golang代碼連接起來,它與mongodb進行通信並將數據返回給節點程序。有什麼方法可以連接嗎?我試圖使用gonode API。這是我使用gonode API的代碼。如何使nodejs與golang交談

我的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 
} 

這是我的錯誤,同時爲節點節點運行越來越.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)

回答

0

基於對生殖器源代碼的草寫檢查,該模塊似乎產生了代碼作爲子進程和通信thro ugh stdin/-out。 EPIPE錯誤意味着另一端關閉了流。基於此,可能會導致您的轉移過程過早退出。

您可以嘗試通過修改gonode/lib/command.js中的Command.prototype.execute來打印出發送到go進程的JSON以調試問題。然後你可以通過直接運行並通過stdin給它輸入相同的輸入來調試go程序。

+0

另外,go代碼示例似乎與您的代碼不同。在函數的開頭,它調用response = make(gonode.CommandData),在if語句中,響應被賦值如下:response [「text」] =「What?」。不太瞭解go,但看起來你的變量m並不與任何東西掛鉤。 https://www.npmjs.com/package/gonode – Juho

2

感謝您的迴應。我爲此得到了一個解決方案。我做了2個不同的服務器。一個用於NodeJS,另一個用於Golang。我在Node服務器中調用golang uri並從golang服務器獲取數據。