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
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:
Both options unfortunately more complicated than console app :(