forked from XTLS/libXray
-
Notifications
You must be signed in to change notification settings - Fork 1
/
xray.go
78 lines (65 loc) · 1.54 KB
/
xray.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// libXray is an Xray wrapper focusing on improving the experience of Xray-core mobile development.
package libXray
import (
"os"
"runtime/debug"
"github.com/xtls/libxray/nodep"
"github.com/xtls/xray-core/common/cmdarg"
"github.com/xtls/xray-core/core"
_ "github.com/xtls/xray-core/main/distro/all"
)
var (
coreServer *core.Instance
)
func startXray(configPath string) (*core.Instance, error) {
file := cmdarg.Arg{configPath}
config, err := core.LoadConfig("json", file)
if err != nil {
return nil, err
}
server, err := core.New(config)
if err != nil {
return nil, err
}
return server, nil
}
func initEnv(datDir string) {
os.Setenv("xray.location.asset", datDir)
}
func setMaxMemory(maxMemory int64) {
nodep.InitForceFree(maxMemory, 1)
}
// Run Xray instance.
// datDir means the dir which geosite.dat and geoip.dat are in.
// configPath means the config.json file path.
// maxMemory means the soft memory limit of golang, see SetMemoryLimit to find more information.
func RunXray(datDir string, configPath string, maxMemory int64) string {
initEnv(datDir)
if maxMemory > 0 {
setMaxMemory(maxMemory)
}
coreServer, err := startXray(configPath)
if err != nil {
return err.Error()
}
if err := coreServer.Start(); err != nil {
return err.Error()
}
debug.FreeOSMemory()
return ""
}
// Stop Xray instance.
func StopXray() string {
if coreServer != nil {
err := coreServer.Close()
coreServer = nil
if err != nil {
return err.Error()
}
}
return ""
}
// Xray's version
func XrayVersion() string {
return core.Version()
}