dongnunai3125 2019-01-02 21:46
浏览 34
已采纳

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!
")
    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, "
")
            }
        }
    }
}
func main() {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

My local CLI works but when I try to wrap it up in a server only so many lines are printed. It's like it times out or something. Help?

I need more text so: I'm parsing a text file.

Edit: here's a test file... https://pastebin.com/ZNbut51X

  • 写回答

1条回答 默认 最新

  • dqwd71332 2019-01-02 21:57
    关注

    You are not helping yourself ignoring errors:

    foo, _ := reader.NextWord() 
    

    This is very bad practice. Check the error and it will tell you what is going on.

    Update:

    You have infinite loop in your code.

    for {
            ...
        }
    

    for{} works until you call continue or return inside that loop.

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

    In your case, it cannot run forever because go-routine that runs it is terminated by timeout.

    Update2:

    Infinite loop is not compatible with HTTP. With web service, you are getting request and should return response before go-routine is terminated by timeout.

    You have two options:

    1. send requests by timer every x seconds and return recent data to caller in handler.
    2. implement technology that supports bidirectional communications between client and server - https://godoc.org/golang.org/x/net/websocket

    Both options unfortunately more complicated than console app :(

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.