From 6037f4b34fc083d7348bc13e2856cfe8182c567d Mon Sep 17 00:00:00 2001 From: Baipyrus Date: Sat, 31 Aug 2024 18:15:50 +0200 Subject: [PATCH] reading and setting system proxy --- go.mod | 1 + go.sum | 2 ++ proxy/types.go | 6 ++++++ proxy/util.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 58 insertions(+) create mode 100644 proxy/types.go create mode 100644 proxy/util.go diff --git a/go.mod b/go.mod index 921f556..5344707 100644 --- a/go.mod +++ b/go.mod @@ -7,4 +7,5 @@ require github.com/spf13/cobra v1.8.1 require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect + golang.org/x/sys v0.24.0 // indirect ) diff --git a/go.sum b/go.sum index 912390a..0bb4413 100644 --- a/go.sum +++ b/go.sum @@ -6,5 +6,7 @@ github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg= +golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/proxy/types.go b/proxy/types.go new file mode 100644 index 0000000..b1a75ec --- /dev/null +++ b/proxy/types.go @@ -0,0 +1,6 @@ +package proxy + +type Proxy struct { + Enabled bool + Server string +} diff --git a/proxy/util.go b/proxy/util.go new file mode 100644 index 0000000..d471ea5 --- /dev/null +++ b/proxy/util.go @@ -0,0 +1,49 @@ +package proxy + +import ( + "errors" + + "golang.org/x/sys/windows/registry" +) + +func ReadSystemProxy() (*Proxy, error) { + key, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Internet Settings`, registry.QUERY_VALUE) + if err != nil { + return nil, err + } + defer key.Close() + + enabled, _, err := key.GetIntegerValue("proxyEnable") + if err != nil { + return nil, err + } + + server, _, err := key.GetStringValue("proxyServer") + if err != nil && !errors.Is(err, registry.ErrNotExist) { + return nil, err + } + + return &Proxy{Enabled: enabled != 0, Server: server}, nil +} + +func SetSystemProxy(state bool) error { + key, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Internet Settings`, registry.SET_VALUE) + if err != nil { + return err + } + defer key.Close() + + var value uint32 + if state { + value = 1 + } else { + value = 0 + } + + err = key.SetDWordValue("proxyEnable", value) + if err != nil { + return err + } + + return nil +}