在Golang中动态加载? [英] Dynamic loading in Golang?

查看:688
本文介绍了在Golang中动态加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个共同的项目和小项目,这些项目在公共项目中扮演着连接器的角色。



我想创建一个通用项目,连接器开发我不需要修改常见项目中的代码。是否有可能在Go中动态加载结构,只知道该结构及其文件夹的路径(通过将此路径放在通用项目的文件中,并在运行时加载该结构)?

  connector1 
connector1.go
/ util
/ domain

connectorN
connectorN.go
/ domain

commonProject
main.go
config.ini

结构config.ini

  Conector 
name = connector1
path = .... / connector1 / connector1.go

Conector
name = connectorN
path = .... / connectorN / connectorN.go

我知道在Java中使用这样的代码可以做到这一点,但我试图在Go中执行此操作。任何想法?

  Class.forName(String)

  ClassLoader.loadClass(String):
code>


解决方案

我可以看到两种方法来实现您所描述的内容,但请记住, @icza指出,go会产生静态的二进制文件,所以你不能动态地加载外部库。

然而,你可以:


  • 使用 cgo 与C代码交互,并加载外部库,即
    方式。 b $ b
  • 使用 net / rpc 包让多个二进制文件相互沟通
    ,并根据需要加载这些文件。


I've got a common project and small projects which act such as connectors in the common project.

I want to create a common project such that when a new connector is developed I don’t have to modify code in the common project. Is it possible to dynamically load the structures in Go, only knowing the path (by putting this path in a file in common project and at runtime load that struct) of the struct and its folders?

connector1
  connector1.go
  /util
  /domain

connectorN
  connectorN.go 
  /domain

commonProject
   main.go
   config.ini

Structure config.ini

Conector
name = connector1
path = ..../connector1/connector1.go

Conector
name = connectorN
path = ..../connectorN/connectorN.go

I know that this is possible to do this in Java with code like this, but I am trying to do this in Go. Any ideas?

Class.forName(String) 

or

ClassLoader.loadClass(String):

解决方案

I can see two ways to achieve what you describe, but keep in mind, as @icza pointed out, that go produces static binaries, so you can't load external libraries dynamically.

You can, however:

  • use cgo to interface with C code, and load external libraries that way.
  • use the net/rpc package to have several binaries communicate with each other, and load those on demand.

这篇关于在Golang中动态加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆