首页 > 解决方案 > 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

标签: parsinggoserver

解决方案


您不会帮助自己忽略错误:

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

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


推荐阅读