78 lines
1.6 KiB
Go
78 lines
1.6 KiB
Go
package ai
|
|
|
|
import (
|
|
"github.com/hashicorp/yamux"
|
|
"log"
|
|
"net"
|
|
"net/http"
|
|
)
|
|
|
|
func startYamuxClient(serverAddr string) {
|
|
// 连接到A服务器
|
|
conn, err := net.Dial("tcp", serverAddr)
|
|
if err != nil {
|
|
log.Fatal("连接A服务器失败:", err)
|
|
}
|
|
log.Printf("已成功连接到A服务器: %s", serverAddr)
|
|
|
|
// 建立yamux会话
|
|
session, err := yamux.Client(conn, nil)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
// 保持连接并处理请求
|
|
for {
|
|
stream, err := session.Accept()
|
|
if err != nil {
|
|
log.Println("accept error:", err)
|
|
continue
|
|
}
|
|
go handleRequest(stream)
|
|
}
|
|
|
|
}
|
|
|
|
func handleRequest(stream net.Conn) {
|
|
log.Printf("收到新连接: 来自 %s", stream.RemoteAddr())
|
|
|
|
mux := http.NewServeMux()
|
|
|
|
mux.HandleFunc("/api/test", func(w http.ResponseWriter, r *http.Request) {
|
|
log.Printf("请求头: %v", r.Header)
|
|
log.Printf("处理测试接口请求")
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.Write([]byte(`{"status":"success","message":"测试接口响应"}`))
|
|
})
|
|
|
|
// 添加默认404处理
|
|
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusNotFound)
|
|
w.Write([]byte("404 - 接口不存在"))
|
|
})
|
|
|
|
http.Serve(&singleConnListener{conn: stream}, mux)
|
|
}
|
|
|
|
type singleConnListener struct {
|
|
conn net.Conn
|
|
}
|
|
|
|
func (l *singleConnListener) Accept() (net.Conn, error) {
|
|
return l.conn, nil
|
|
}
|
|
|
|
func (l *singleConnListener) Close() error {
|
|
return nil
|
|
}
|
|
|
|
func (l *singleConnListener) Addr() net.Addr {
|
|
return l.conn.LocalAddr()
|
|
}
|
|
|
|
func main() {
|
|
// 这里可以添加命令行参数解析
|
|
serverAddr := "client_url:1234" // P端Client服务地址
|
|
startYamuxClient(serverAddr)
|
|
}
|