gpt4 book ai didi

html - 使用fmt.Fprintf()发送文本/纯文本

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

我正在使用fmt.Printf(string)遇到一个非常奇怪的(希望很容易修复)问题

我有一个使用net.Listener()侦听端口8080上的连接的GO应用程序。

使用网络浏览器,我连接到服务器。服务器接收到连接后,它将接受并以以下代码响应(我已删除了错误处理)

func main() {
socket, _ := net.Listen("tcp", ":8080")

for {
connection, _ := socket.Accept()
go handleClient(connection)
}
}


// Function called as a go routine by main after accepting a connection
func handleClient(c net.Conn) {
defer c.Close()

r := bufio.NewReader(c)
for {
// Read each header line individually
req, err := r.ReadString('\n')
if err != nil && err != io.EOF {
// Call function that prints the error to the console
checkError(err)
}

// Show request headers in terminal
fmt.Print(req)

// Stop reading request headers
if len(req) <= 2 {
break
}
}

// Create generic response headers - for testing only
var headers = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 70\r\nConnection: keep-alive\r\n\r\n"

// Get current dir path
pwd, _ := os.Getwd()

// Read a file (content says "This is a test, five times"
body, err := ioutil.ReadFile(pwd + "/test.txt")
if err != nil {
checkError(err)
}

// Print to terminal
fmt.Println(headers + string(body))

// Send to client
fmt.Fprintf(c, headers + string(body))

我的终端会打印出(标题+正文),并根据需要准确显示内容。标头,然后是\ r \ n,然后是HTML内容。但是,我的网络浏览器仅显示:
1) This is a test
2) This is a test
3) This is a test
4) This is a tes

我的终端显示了所有5行(浏览器显示4行),而第4行缺少最后一个字符。我需要设置某种形式的缓冲区吗?

最后,这是学校的任务,我们被告知不要使用使这样做更容易的库(例如HTTP GO库)。

谢谢你的帮助。

编辑:现在已经发布了整个功能。请注意,最后两行显示相同的内容。控制台会准确地显示文本,如我预期的那样。打印到客户端会中断一定数量的字节。即使我做大一行,它仍然会在某些时候停止打印。

编辑2:我添加了一行读取文件。我的浏览器可以很好地读取文件,但是我有同样的问题。内容被截断。

最佳答案

在发送其他响应之前,请尝试将其发送到浏览器:

fmt.Fprintf(c, "HTTP/1.0 200 OK\r\n")
fmt.Fprintf(c, "Content-Type: text/plain\r\n")
fmt.Fprintf(c, "\r\n")

关于html - 使用fmt.Fprintf()发送文本/纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43713065/

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