2022-01-10 14:56:41 +00:00
|
|
|
package util
|
|
|
|
|
|
|
|
import (
|
2024-08-21 08:19:59 +00:00
|
|
|
"errors"
|
2022-05-13 09:49:05 +00:00
|
|
|
"fmt"
|
2022-01-10 14:56:41 +00:00
|
|
|
"os/exec"
|
|
|
|
"runtime"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2024-08-21 08:19:59 +00:00
|
|
|
const getDefaultNetworkCMD = "networksetup -listnetworkserviceorder | grep" +
|
|
|
|
" `(route -n get default | grep 'interface' || route -n get -inet6 default | grep 'interface') | cut -d ':' -f2`" +
|
|
|
|
" -B 1 | head -n 1 | cut -d ' ' -f 2-"
|
|
|
|
|
2022-05-13 09:49:05 +00:00
|
|
|
func SetOsProxy(port int) error {
|
2022-01-10 14:56:41 +00:00
|
|
|
if runtime.GOOS != "darwin" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-08-21 08:19:59 +00:00
|
|
|
network, err := getDefaultNetwork()
|
2022-01-10 14:56:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2024-08-21 08:19:59 +00:00
|
|
|
args := fmt.Sprintf("'%s' 127.0.0.1 %d", network, port)
|
|
|
|
|
|
|
|
_, err = exec.Command("sh", "-c", "networksetup -setwebproxy "+args).Output()
|
2022-01-10 14:56:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2024-08-21 08:19:59 +00:00
|
|
|
_, err = exec.Command("sh", "-c", "networksetup -setsecurewebproxy "+args).Output()
|
2022-01-10 14:56:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func UnsetOsProxy() error {
|
|
|
|
if runtime.GOOS != "darwin" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-08-21 08:19:59 +00:00
|
|
|
network, err := getDefaultNetwork()
|
2022-01-10 14:56:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2024-08-21 08:19:59 +00:00
|
|
|
_, err = exec.Command("sh", "-c", "networksetup -setwebproxystate "+"'"+network+"'"+" off").Output()
|
2022-01-10 14:56:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2024-08-21 08:19:59 +00:00
|
|
|
_, err = exec.Command("sh", "-c", "networksetup -setsecurewebproxystate "+"'"+network+"'"+" off").Output()
|
2022-01-10 14:56:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2024-08-21 08:19:59 +00:00
|
|
|
|
|
|
|
func getDefaultNetwork() (string, error) {
|
|
|
|
network, err := exec.Command("sh", "-c", getDefaultNetworkCMD).Output()
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
} else if len(network) == 0 {
|
|
|
|
return "", errors.New("no available networks")
|
|
|
|
}
|
|
|
|
return strings.TrimSpace(string(network)), nil
|
|
|
|
}
|