刷新后如何打印下一行?

时间:2018-11-19 02:28:41

标签: go

我想创建一个/health来显示歌曲的每一行。我试图在刷新页面后显示歌曲的下一行,但是下面的代码不起作用,我也不知道丢失了什么。

期望

每次刷新后,它应该从歌曲返回不同的行。

➜ curl http://localhost:8080/health
It starts with one thing

➜ curl http://localhost:8080/health
I don't know why

➜ curl http://localhost:8080/health
It doesn't even matter how hard you try

现实

➜ curl http://localhost:8080/health
It starts with one thing

➜ curl http://localhost:8080/health
It starts with one thing

➜ curl http://localhost:8080/health
It starts with one thing

以下是main.gotestlib.go中的几行。

testlib.go

func GetLine() func() string {
    n := 0
    lines := strings.Split(readFile(), "\n")
    length := len(lines) - 1

    return func() string {
        nextLine := lines[n]

        if n == length {
            n = 0

            return nextLine
        }

        n++
        return nextLine
    }
}

func Handler(next http.HandlerFunc) http.HandlerFunc {
    return func (w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "text/plain; charset=utf-8")
        log.Println(r.URL.Path)
        next.ServeHTTP(w, r)
    }
}

main.go

func health(w http.ResponseWriter, r *http.Request) {
    line := testlib.GetLine()

    fmt.Fprintln(w, line())
}

func main() {
    http.Handle("/health", testlib.Handler(health))
    log.Printf("http://127.0.0.1:8080 is now listening.")

    if err := http.ListenAndServe("127.0.0.1:8080", nil); err != nil {
        log.Fatal(err)
    }
}

1 个答案:

答案 0 :(得分:0)

由于n是局部变量,因此每次调用0函数时,它将始终用值GetLine()进行重新声明。可能是您需要一个全局变量来保存最后一行的值:D