登录
首页 >  Golang >  Go问答

如何捕获`runtime.Goexit()`信号

来源:stackoverflow

时间:2024-02-28 14:06:15 123浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《如何捕获`runtime.Goexit()`信号》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

package main

import  (
    "github.com/fatih/color"
    "github.com/gin-gonic/gin"
    "runtime"
)

var (
    Errors map[string]string
    err error
)

func CheckErr(err error) {
    if err != nil {
        pc, file, line, _ := runtime.Caller(1)
        color.New(color.FgRed).PrintfFunc()(" [app]")
        color.New(color.FgMagenta).PrintfFunc()("%v:", time.Now().Format("15:04:05.00000"))
        color.New(color.FgGreen).PrintfFunc()("%v] %v:%v:", path.Ext(runtime.FuncForPC(pc).Name())[1:], path.Base(file), line)
        color.Yellow(" %v", err)
        Errors["app "+time.Now().Format("15:04:05.00000")+" "+path.Ext(runtime.FuncForPC(pc).Name())[1:]+" "+path.Base(file)+":"+strconv.Itoa(line)] = err.Error()
        runtime.Goexit()
    }
}

func test(hello string) string{
    // ...
    if err!=nil{
        CheckErr(err)
    } 
    text := hello+" world"
    return test
}

func main() {
    req.POST("/hello", func(context *gin.Context) {
        message:=test("hello")
        context.JSON(200, gin.H{
            "message": message,
            "Errors": Errors,
        })
    }
}
  • checkerr是一个收集错误日志、打印错误并退出的函数
  • 主要是杜松子酒服务
  • test是gin的数据采集函数
  • 无法使用 go 协程,因为 test 需要返回数据

当测试失败时如何返回gin并返回错误消息?


正确答案


如果你坚持使用 runtime.goexit() 那么你必须使用另一个 goroutine。与 chansync.waitgroup 一起使用效果很好,因为 goexit 运行所有延迟调用。

func CheckErr(err error, done chan struct{}) {
    defer func() { done <- struct{}{} }()
    if err != nil {
        // ...
        runtime.Goexit()
    }
}


func test(hello string) string {
    // ...
    if err != nil {
        done := make(chan struct{})
        go CheckErr(err, done)
        <-done
    }
    text := hello + " world"
    return text
}

本篇关于《如何捕获`runtime.Goexit()`信号》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>