Не удалось преобразовать файл Go в JS - PullRequest
0 голосов
/ 08 апреля 2020

Я пытаюсь запустить go файлы как модули, используя: https://github.com/sagiegurari/node-go-require и https://github.com/gopherjs

У меня нет ошибок в моем go код, но при использовании приведенного ниже JS я сталкиваюсь с 'Ошибка: не удалось преобразовать Go файл в JS'

Вот мой nodeJS код:

    require('node-go-require');
    //Failing here
    const Phantom = require(__dirname + '/source/cmd/phantom.go').phantom;

    var params = {
        server:null,
        boundIP:null,
        boundPort:null,
        timeOut:null
    }

    //Some other code here to set params

    function start(){

        //determine which parameters have been set by user
        var args = [params.server];

        if(params.boundIP != null){
            args.push(params.boundIP);
        } else {
            args.push("0.0.0.0");
        }

        if(params.boundPort != null){
            args.push(params.boundPort);
        } else {
            args.push(0);
        }

        if(params.timeOut != null){
            args.push(params.timeOut);
        } else {
            args.push(60);
        }

        var p = Phantom.new(...args);

     }

Вот мой основной go файл:

package main

import (
    "github.com/gopherjs/gopherjs/js"
    "github.com/jhead/phantom/internal/proxy"
)


func main() {

    js.Module.Get("exports").Set("phantom", map[string]interface{}{
        "new": proxy.New,
    })

}

Вот прокси. Новая функция:

package proxy

import (
    "fmt"
    "math/rand"
    "net"
    "time"

    "github.com/gopherjs/gopherjs/js"
    "github.com/jhead/phantom/internal/clientmap"
    "github.com/jhead/phantom/internal/logging"
    "github.com/jhead/phantom/internal/proto"
    "github.com/tevino/abool"

    reuse "github.com/libp2p/go-reuseport"
)

var idleCheckInterval = 5 * time.Second

type ProxyServer struct {
    bindAddress         *net.UDPAddr
    remoteServerAddress *net.UDPAddr
    pingServer          net.PacketConn
    server              *net.UDPConn
    clientMap           *clientmap.ClientMap
    prefs               ProxyPrefs
    dead                *abool.AtomicBool
}

type ProxyPrefs struct {
    BindAddress  string
    BindPort     uint16
    RemoteServer string
    IdleTimeout  time.Duration
}

func New(BindAddress string, BindPort uint16, RemoteServer string, IdleTimeout time.Duration) *js.Object {

    var prefs = new(ProxyPrefs)
    prefs.BindAddress = BindAddress
    prefs.BindPort = BindPort
    prefs.RemoteServer = RemoteServer
    prefs.IdleTimeout = time.Duration(IdleTimeout) * time.Second

    bindPort := prefs.BindPort

    // Randomize port if not provided
    if bindPort == 0 {
        randSource := rand.NewSource(time.Now().UnixNano())
        bindPort = (uint16(randSource.Int63()) % 14000) + 50000
    }

    // Format full bind address with port
    prefs.BindAddress = fmt.Sprintf("%s:%d", prefs.BindAddress, bindPort)

    bindAddress, err := net.ResolveUDPAddr("udp", prefs.BindAddress)
    if err != nil {
        return nil
    }

    remoteServerAddress, err := net.ResolveUDPAddr("udp", prefs.RemoteServer)
    if err != nil {
        return nil
    }

    return js.MakeWrapper(&ProxyServer{
        bindAddress,
        remoteServerAddress,
        nil,
        nil,
        clientmap.New(prefs.IdleTimeout, idleCheckInterval),
        *prefs,
        abool.New(),
    })
}

Если кто-нибудь может помочь, это будет очень цениться, так как я почти fre sh до GO.

Вот что я работаю для контекста: https://github.com/OliverBrotchie/phantom

1 Ответ

0 голосов
/ 08 апреля 2020

Вы должны запустить gopher js вручную, чтобы увидеть фактическую ошибку: например:

/workspace/go/bin/gopherjs  build /workspace/phantom/source/cmd/phantom.go

Одна проблема может быть, например, в том, что среда выполнения go слишком старая или слишком новая. как только вы увидите проблему, скорее всего, к go, где можно обратиться за помощью, будет страница проекта gopher js github по адресу https://github.com/gopherjs/gopherjs, где вы можете сразу же открыть проблемы.

поскольку no- go -require - это всего лишь прокси-сервер (в основном, для обеспечения возможности бесшовного узла требовать для файлов go), я не стал бы пытаться найти проблему там.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...