Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make nodejs to talk with golang

I am creating a web app in node.js and golang. I need to connect nodejs with golang code which talks to mongodb and returns data to node program. is there any way to connect so? I tried to use gonode API.This is my code using gonode API.

my node.js file contains below code:

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();
});     `

And this is the code in my gofile.go file:

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
}

This is the error am getting while running as node node.js in terminal

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: write EPIPE
    at errnoException (net.js:905:11)
    at Object.afterWrite (net.js:721:19)
like image 546
Murali Manohar Avatar asked Jun 20 '15 08:06

Murali Manohar


1 Answers

Golang from 1.5, you can build go to shared object binary file (*.so). This allows you to connect your go compiled library to be called by nodejs, python, ruby, java etc.

Here is a guide you could refer to: https://medium.com/learning-the-go-programming-language/calling-go-functions-from-other-languages-4c7d8bcc69bf

like image 125
Howard Avatar answered Oct 04 '22 21:10

Howard