gpt4 book ai didi

go - TCP 客户端无法正常工作 golang

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

我有一个用 golang 编写的 rest-ful 界面。我需要在每个端点上进行身份验证。身份验证完成后,我必须将其转发回 tcp 服务器。我创建了一个 tcp 客户端,来自 channel 的任何值都将发送到 tcp 服务器。该 channel 是从 http 请求正文中填充的。问题是,一旦我发出 curl 命令,客户端就会卡住,没有任何响应;所以很明显我做错了什么不知道错在哪里。有人对我的问题可能有什么见解吗?

 package main

import (
"bufio"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strconv"

auth "github.com/abbot/go-http-auth"
)

type Configuration struct {
Server string
Port int64
UserName string
Pwd string
Realm string
ProxyPort int64
Edeserver string

}

var (
Config *Configuration
logp = flag.Bool("log", false, "enable logging")
)

func ReadConfiguration() {
file, _ := os.Open("Config.json")
decoder := json.NewDecoder(file)
Config = &Configuration{}
err := decoder.Decode(&Config)
if err != nil {
fmt.Println("error:", err)
}

}

func Secret(user, realm string) string {
if user == Config.UserName {
// password is "hello"
return Config.Pwd
}
return ""
}

func reverseProxyTows(w http.ResponseWriter, authenticatedRequest *auth.AuthenticatedRequest) {
req := &authenticatedRequest.Request

if *logp {
log.Println(" Authenticated Username ", authenticatedRequest.Username)
log.Println(" Authenticated URL ", req.URL.RequestURI())
}

destinationURL := fmt.Sprintf("http://%s:%d", Config.Server, Config.Port)
u, err := url.Parse(destinationURL)
if err != nil {
log.Fatal(err)
}

if *logp {
log.Println("reverse_proxy", u)
}

reverseProxy := httputil.NewSingleHostReverseProxy(u)

reverseProxy.ServeHTTP(w, req)
}

func openConnectionTotcp(edechannel chan string) {
conn, _ := net.Dial("tcp", Config.Edeserver)
text := <-edechannel
fmt.Fprintf(conn, text+"\n")
message, _ := bufio.NewReader(conn).ReadString('\n')
fmt.Print("Message from server: " + message)
}


func main() {
ReadConfiguration()
flag.Parse()
c := make(chan string)
go openConnectionTotcp(c)

fmt.Printf("Started proxy to destination server %v:%d and is listening on %d ", Config.Server, Config.Port, Config.ProxyPort)

authenticator := auth.NewBasicAuthenticator(Config.Realm, Secret)
http.HandleFunc("/", authenticator.Wrap(reverseProxyTows))
http.HandleFunc("/tyrion/1", authenticator.Wrap(func(w http.ResponseWriter, authenticatedRequest *auth.AuthenticatedRequest) {
req := &authenticatedRequest.Request
bodyBytes, err2 := ioutil.ReadAll(req.Body)
if err2 != nil {
log.Fatal(err2)
}
bodyString := string(bodyBytes)
c <- bodyString
fmt.Fprintf(w, "success")
}))
http.ListenAndServe(":"+strconv.FormatInt(Config.ProxyPort, 10), nil)
}

最佳答案

您的代码执行 block 在 c <- bodyString因为似乎没有从那个无缓冲 channel 读取任何东西。该行将暂停执行,直到另一个例程从 channel 读取。

关于go - TCP 客户端无法正常工作 golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43625720/

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