mirror of
https://github.com/shtorm-7/sing-box-extended.git
synced 2026-05-30 07:54:23 +03:00
Add daemon support
This commit is contained in:
58
experimental/daemon/instance.go
Normal file
58
experimental/daemon/instance.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/sagernet/sing-box"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
)
|
||||
|
||||
type Instance struct {
|
||||
access sync.Mutex
|
||||
boxInstance *box.Box
|
||||
boxCancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (i *Instance) Running() bool {
|
||||
i.access.Lock()
|
||||
defer i.access.Unlock()
|
||||
return i.boxInstance != nil
|
||||
}
|
||||
|
||||
func (i *Instance) Start(options option.Options) error {
|
||||
i.access.Lock()
|
||||
defer i.access.Unlock()
|
||||
if i.boxInstance != nil {
|
||||
i.boxCancel()
|
||||
i.boxInstance.Close()
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
instance, err := box.New(ctx, options)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return err
|
||||
}
|
||||
err = instance.Start()
|
||||
if err != nil {
|
||||
cancel()
|
||||
return err
|
||||
}
|
||||
i.boxInstance = instance
|
||||
i.boxCancel = cancel
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *Instance) Close() error {
|
||||
i.access.Lock()
|
||||
defer i.access.Unlock()
|
||||
if i.boxInstance == nil {
|
||||
return os.ErrClosed
|
||||
}
|
||||
i.boxCancel()
|
||||
err := i.boxInstance.Close()
|
||||
i.boxInstance = nil
|
||||
i.boxCancel = nil
|
||||
return err
|
||||
}
|
||||
Reference in New Issue
Block a user