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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号