1 回答

TA貢獻1820條經驗 獲得超3個贊
正如目前所寫的,當瀏覽器請求時,在完成之前不會返回任何內容(這將需要大約150秒)。完成后,將返回/顯示帶有的頁面。如果你想為用戶提供中斷過程的能力,那么最好在Goroutine中運行它;像這樣:/toggleEnableSum()Sum()Test enabled : false
// Settings Type ...
type Settings struct {
Enabled bool
Stop chan struct{}
}
var settings Settings
type Template struct {
templates *template.Template
}
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return t.templates.ExecuteTemplate(w, name, data)
}
func toggleEnable(c echo.Context) error {
if settings.Enabled {
settings.Enabled = false
close(settings.Stop)
} else {
settings.Enabled = true
settings.Stop = make(chan struct{})
go Sum(settings.Stop)
}
return c.Redirect(http.StatusTemporaryRedirect, c.Request().Header.Get("Referer"))
}
func Sum(stop chan struct{}) {
sum := 0
for i := 1; i < 50; i++ {
sum += i
fmt.Println(sum)
select {
case <-stop:
fmt.Println("stopped")
return
case <-time.After(3 * time.Second):
}
}
}
請注意,這存在一些問題。它是在假設將有一個客戶端并且計時器完成時頁面不會更新的假設下編寫的(您需要添加刷新或類似內容)。
下一步是在html頁面中顯示計數
為此,您需要一種瀏覽器請求更新的方法。這可能是通過刷新(相當簡單但不是很好的用戶體驗)或使用Javascript(輪詢或使用websockets)
- 1 回答
- 0 關注
- 79 瀏覽
添加回答
舉報