go - 刷新后如何打印下一行?

标签 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)
    }
}

ma​​in.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)
    }
}

最佳答案

因为 n 是局部变量,所以每当您调用 GetLine() 函数时,它总是会重新声明为 0。可能你需要一个全局变量来保存最后一行的值 :D

关于go - 刷新后如何打印下一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53367526/

相关文章:

go - 如何删除多级 map

go - 如何在 golang 中为我的测试用例正确创建模拟 http.request?

docker - 无法从 Docker 容器内的 Google API 交换 AccessToken

loops - 为什么无限循环不递增整数?

go - 如何让 VSCode 为同一个 repo 中的不同目录使用不同的 Go env vars?

api - 语法错误 : need trailing comma before newline in composite literal

go - Go光纤未在本地主机上运行

golang 如何使用工具找到 ticker 泄漏的位置?

json - 存储和检索 RSA 加密 key

rest - 在 REST 上不支持的 HTTP 方法返回什么响应代码?