easytier golang 集成简单试用
easytier 是基于rust 编写的,官方目前提供了ffi 包,c# 以及提供了示例了对于golang 我们基于cgo 也就可以了,以下是一个简单示例,主要是测试下golang 与easytier ffi 的集成
编译ffi
我使用的是mac 系统,先编译ffi,这个比较简单直接cargo build --release就可以了
cgo 集成
对于cgo 核心是定义header 文件,以及使用
- 项目结构
├── app.yaml # app.yaml 配置
├── go.mod
├── include
│ └── easytier.h # header 定义
├── lib
│ └── libeasytier_ffi.dylib # 编译的ffi 动态库
└── main.go
- easytier.h
核心是参考官方的进行调整支持
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
const char* key;
const char* value;
} KeyValuePair;
void get_error_msg(const char **out);
void free_string(char* s);
int32_t parse_config(const char* cfg_str);
int32_t run_network_instance(const char* cfg_str);
int32_t retain_network_instance(const char** inst_names, uintptr_t length);
int32_t collect_network_infos(KeyValuePair* infos, uintptr_t max_length);
- main.go
package main
// 标准cgo 玩法,定义头文件,以及依赖的库
/*
#cgo CFLAGS: -I./include
#cgo LDFLAGS: -L./lib -leasytier_ffi
#include "easytier.h"
*/
import "C"
import (
"fmt"
"os"
"time"
"unsafe"
)
func main() {
// 此处是配置,方便调整
data, err := os.ReadFile("app.yaml")
if err != nil {
panic(err)
}
content := string(data)
configPath := C.CString(content)
defer C.free(unsafe.Pointer(configPath))
result := C.parse_config(configPath)
fmt.Println(result)
// 运行easytier 网络,注意应该是一个long running 任务
result = C.run_network_instance(configPath)
if result != 0 {
fmt.Printf("Error running network instance: %d\n", result)
} else {
fmt.Println("Network instance started successfully")
for {
fmt.Println("looping...")
time.Sleep(1 * time.Second)
}
}
}
- app.yaml
就是配置,调整为自己的,或者公网的
instance_name = "easytier"
instance_id = "2d97d178-8f67-4003-b286-6d47fa9dbed3"
dhcp = true
listeners = [
"tcp://0.0.0.0:11010",
"udp://0.0.0.0:11010",
"wg://0.0.0.0:11011",
]
rpc_portal = "0.0.0.0:0"
[network_identity]
network_name = "xxxx"
network_secret = "xxxxxx"
[[peer]]
uri = "tcp://xxxxxx:11010"
[flags]
说明
以上是一个简单的运行,事实上我们也可以基于purego 进行包装使用外部库,以上代码经过测试是可以运行的
参考资料
https://github.com/rongfengliang/easytier-ffi-cgo
https://github.com/ebitengine/purego
https://easytier.cn/web/index.html#/config_generator
https://github.com/EasyTier/EasyTier/tree/main/easytier-contrib/easytier-ffi