gpt4 book ai didi

parsing - X 后响应退出

转载 作者:IT王子 更新时间:2023-10-29 01:46:46 31 4
gpt4 key购买 nike

package main

import (
"fmt"
"log"
"net/http"
"os"

"github.com/steven-ferrer/gonsole"
)

func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there!\n")
file, err := os.Open("ItemLog.txt")
if err != nil {
log.Fatal(err)
}

reader := gonsole.NewReader(file)
counter := 0
for {
foo, _ := reader.NextWord()
if foo == "<Kept>" {
counter++
fmt.Fprintf(w, "%d"+": ", counter)
foo, _ = reader.NextWord()
for foo != "|" {
fmt.Fprintf(w, foo+" ")
foo, _ = reader.NextWord()
}
if foo == "|" { // need to reader.NewLine instead but this will work for now.
fmt.Fprintf(w, "\n")
}
}
}
}
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}

我的本​​地 CLI 可以工作,但是当我尝试将其包装在服务器中时,只打印了那么多行。好像超时了之类的。帮忙?

我需要更多文本:我正在解析一个文本文件。

编辑:这是一个测试文件... https://pastebin.com/ZNbut51X

最佳答案

您不是在帮助自己忽略错误:

foo, _ := reader.NextWord() 

这是非常糟糕的做法。检查错误,它会告诉您发生了什么。

更新:

你的代码中有无限循环。

for {
...
}

for{} 一直有效,直到您在该循环内调用 continuereturn

https://tour.golang.org/flowcontrol/4

在您的情况下,它不能永远运行,因为运行它的 go-routine 因超时而终止。

更新2:

无限循环与 HTTP 不兼容。使用 Web 服务,您将收到请求并且应该在 go-routine 因超时终止之前返回响应。

你有两个选择:

  1. 每隔 x 秒通过定时器发送请求并将最近的数据返回给处理程序中的调用方。
  2. 实现支持双向通信的技术客户端和服务器之间 - https://godoc.org/golang.org/x/net/websocket

不幸的是,这两个选项都比控制台应用程序更复杂:(

关于parsing - X 后响应退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54013573/

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