| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- package main
- import (
- "context"
- "coredemo/framework"
- "fmt"
- "time"
- )
- func FooControllerHandler(ctx *framework.Context) error {
- // 这个 channal 负责通知结束
- finish := make(chan struct{}, 1)
- // 这个 channel 负责通知 panic 异常
- panicChan := make(chan interface{}, 1)
- durationCtx, cancel := context.WithTimeout(ctx.BaseContext(), time.Duration(5*time.Second))
- defer cancel()
- {
- // 增加异常处理
- if p := recover(); p != nil {
- panicChan <- p
- }
- }
- go func() {
- // 这里做具体的业务
- time.Sleep(10 * time.Second)
- ctx.Json(200, "ok")
- // 结束的时候通过一个 finish 通道告知父 goroutine
- finish <- struct{}{}
- }()
- select {
- // 监听 panic
- case <-panicChan:
- ctx.WriterMux().Lock()
- defer ctx.WriterMux().Unlock()
- ctx.Json(500, "panic")
- // 监听结束
- case <-finish:
- fmt.Println("finish")
- // 监听超时
- case <-durationCtx.Done():
- ctx.WriterMux().Lock()
- defer ctx.WriterMux().Unlock()
- ctx.Json(500, "time out")
- // 这里记得设置标记
- ctx.SetHasTimeout()
- }
- return ctx.Json(200, map[string]interface{}{
- "code": 0,
- })
- }
|