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.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)
}
}
解决方案
因为是局部变量,所以每当您调用该函数时n
,它总是会用值重新声明。可能您需要一个全局变量来保存最后一行的值:D0
GetLine()
推荐阅读
- c++ - 使用 C++ 解析复杂的文本文件
- javascript - 引导电子邮件输入中的wordpress jetpack不需要的边框
- java - 包含链接文本的下拉列表中的 getText() 返回空字符串
- python - 如何链接散景输入/控件以过滤数据?无法弄清楚如何使输入过滤掉视觉中显示的值
- php - 如何在实体实例中检索请求或语言环境?
- sql - 需要帮助在 Postgres 函数中设置 Json 键值
- php - 由于目标机器主动拒绝,无法建立连接。Laravel 5.7 尝试连接 MsSQL 服务器
- python - 如何将 unicode 转换为可读字符串?
- django - 在 Django 项目中出现“MultiValueDictKeyError at /button/'text”错误
- ios - 如何在不损失质量的情况下放大微小的文本图像?