parsing - X 后响应退出
问题描述
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{}
一直有效,直到您调用continue
或return
在该循环内。
https://tour.golang.org/flowcontrol/4
在您的情况下,它不能永远运行,因为运行它的 go-routine 会因超时而终止。
更新2:
无限循环与 HTTP 不兼容。使用 Web 服务,您会收到请求,并且应该在 go-routine 因超时而终止之前返回响应。
你有两个选择:
- 每 x 秒通过计时器发送请求,并将最近的数据返回给处理程序中的调用者。
- 实现支持客户端和服务器之间双向通信的技术 - https://godoc.org/golang.org/x/net/websocket
不幸的是,这两个选项都比控制台应用程序复杂:(
推荐阅读
- ruby - Rubocop 使用错误版本的 Ruby - 失败
- c++ - 我可以/应该在#ifndef 之后输入我想要的任何内容吗?
- javascript - Bootstrap jquery hidden and shown.bs.modal 模态属性不起作用
- python - 一组文本文件之间的文档相似性
- typescript - 使用 Typescript 从对象中获取值
- vb.net - 使用 backgroundworker 时强制转换无效
- c# - C# - 从线程更新 windows 窗体元素
- javascript - 如何检查javascript数组是否包含具有特定值的属性,如果是则返回true
- java - 由已分配的 ByteString 支持的高效 okio 源?
- matlab - 如何在matlab中重写多个for循环以优化速度?