gpt4 book ai didi

sockets - 无需使用 http.Serve 即可激活 Go TLS Socket 服务器服务

转载 作者:数据小太阳 更新时间:2023-10-29 03:20:34 25 4
gpt4 key购买 nike

我有以下代码和 systemd 单元文件。我想要做的是激活监听器,而不必使用 http.Serve 来接受和接收传入连接。如果我将 ln, err := tls.Listen("tcp", listen, config) 更改为 ln, err := activation.TLSListener(config) 我看到我可以接收数据的唯一方法是使用 http.Serve。我在使用 ln, err := activation.TLSListeners.(config) 时得到的错误是 ln.Accept undefined (type []net.Listener has no field or method Accept)

package main

import (
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"time"

"github.com/coreos/go-systemd/daemon"
"github.com/coreos/go-systemd/journal"
"github.com/coreos/go-systemd/activation"
)

func createServerConfig(ca, crt, key string) (*tls.Config, error) {
caCertPEM, err := ioutil.ReadFile(ca)
if err != nil {
return nil, err
}

roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM(caCertPEM)
if !ok {
panic("failed to parse root certificate")
}

cert, err := tls.LoadX509KeyPair(crt, key)
if err != nil {
return nil, err
}
return &tls.Config{
Certificates: []tls.Certificate{cert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: roots,
}, nil
}

const (
ca = "/home/ajames/Shortcuts/Link to MainGoFolder/Workspace/servicecode/tls-server/certs/ca-chain.cert.pem"
crt = "/home/ajames/Shortcuts/Link to MainGoFolder/Workspace/servicecode/tls-server/certs/tls-server2-SAN.pem"
key = "/home/ajames/Shortcuts/Link to MainGoFolder/Workspace/servicecode/tls-server/certs/tls-server2-SAN.key"
listen = "127.0.0.1:4433"
)

func main() {

if journal.Enabled() {
journal.Print(journal.PriInfo, "all systems ready...")
}

p := fmt.Println
now := time.Now()
p(now)

config, err := createServerConfig(ca, crt, key)
if err != nil {
log.Fatal("config failed: %s", err.Error())
}

ln, err := tls.Listen("tcp", listen, config)
if err != nil {
log.Fatal("listen failed: %s", err.Error())
}
daemon.SdNotify(false, "READY=1")
log.Printf("listen on %s", listen)

go func() {
interval, err := daemon.SdWatchdogEnabled(false)
if err != nil || interval == 0 {
return
}
for {
daemon.SdNotify(false, "WATCHDOG=1")
time.Sleep(interval / 3)
}
}()

for {
conn, err := ln.Accept()
if err != nil {
log.Fatal("accept failed: %s", err.Error())
break
}
log.Printf("connection open: %s", conn.RemoteAddr())
//printConnState(conn.(*tls.Conn))

go func(c net.Conn) {
wr, _ := io.Copy(c, c)
c.Close()
log.Printf("connection close: %s, written: %d", conn.RemoteAddr(), wr)
}(conn)
}
}


[Unit]
Description=tls server service
After=network.target tls-server.socket
Requires=tls-server.socket

[Service]
Type=notify
WatchdogSec=30s
StandardInput=socket
StandardError=journal
ExecStart=/usr/local/bin/tls-server
NonBlocking=true
Restart=on-failure

[Install]
WantedBy=multi-user.target


[Unit]
Description=tls server socket
StartLimitIntervalSec=10
PartOf=tls-server.service
After=network.target

[Socket]
ListenStream=127.0.0.1:4433
NoDelay=true
Accept=true
ReusePort=true
MaxConnections=200
Writable=true

[Install]
WantedBy=sockets.target

最佳答案

I found a solution that works. The answer came from https://www.darkcoding.net/software/systemd-socket-activation-in-go/.

My new code looks like this

package main

import (
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"strconv"
"time"

"github.com/coreos/go-systemd/journal"
)

func createServerConfig(ca, crt, key string) (*tls.Config, error) {
caCertPEM, err := ioutil.ReadFile(ca)
if err != nil {
return nil, err
}`enter code here`

roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM(caCertPEM)
if !ok {
panic("failed to parse root certificate")
}

cert, err := tls.LoadX509KeyPair(crt, key)
if err != nil {
return nil, err
}
return &tls.Config{
Certificates: []tls.Certificate{cert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: roots,
}, nil
}

const (
ca = "/usr/local/bin/certs/ca-chain.cert.pem"
crt = "/usr/local/bin/certs/tls-server2-SAN.pem"
key = "/usr/local/bin/certs/tls-server2-SAN.key"
BUFFER_SIZE = 1024`enter code here`
)

func main() {
if journal.Enabled() {
journal.Print(journal.PriInfo, "all systems ready...")
}

p := fmt.Println
now := time.Now()
p(now)

config, err := createServerConfig(ca, crt, key)
if err != nil {
log.Fatal("config failed: %s", err.Error())
}
if os.Getenv("LISTEN_PID") == strconv.Itoa(os.Getpid()) {
// systemd run
f := os.NewFile(3, "from systemd")
ln, err := net.FileListener(f)
if err != nil {
log.Fatal(err)
}
tlsListener := tls.NewListener(ln, config)
for {
conn, err := tlsListener.Accept()
if err != nil {
log.Fatal("accept failed: %s", err.Error())
break
}
log.Printf("connection open: %s", conn.RemoteAddr())
//printConnState(conn.(*tls.Conn))
go func(c net.Conn) {
wr, _ := io.Copy(c, c)
c.Close()
log.Printf("connection close: %s, written: %d", conn.RemoteAddr(), wr)
}(conn)
}`enter code here`
}
}

关于sockets - 无需使用 http.Serve 即可激活 Go TLS Socket 服务器服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54621640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com