搜索
首页后端开发Golang如何在 Go 中优雅地处理和终止 HTTP 请求?

How to Gracefully Handle and Terminate HTTP Requests in Go?

终止或中止 HTTP 请求

要处理 API 处理期间的错误,终止或中止请求至关重要。虽然像 log.fatal 和 os.Exit 这样的选项可能会终止整个服务,但它们会阻碍错误消息的传递。本文探讨了使用panic、defer、recover和return的替代方法。

使用return进行错误处理

最简单的方法是从ServeHTTP()函数返回:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    // Check parameters
    if !ok {
        str := `{"Result":"","Error":"Invalid Parameters"}`
        fmt.Fprint(w, str)
        return // Terminates the request
    }

    // Normal API handling
})

这种方法对于主 HTTP 处理函数来说效果很好,但在嵌套函数中,它只存在函数,而不存在调用者。

HTTP 错误代码和自定义响应

考虑返回适当的 HTTP 错误代码,而不是默认的 200 OK 响应代码。 http.Error() 允许自定义错误消息:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    if !ok {
        http.Error(w, `Invalid Input Parameters!`, http.StatusBadRequest)
        return
    }

    // Normal API handling
})

要进行更精细的控制,您可以设置自定义内容类型和响应正文:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    if !ok {
        w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(http.StatusBadRequest)
        str := `{"Result":"","Error":"Invalid Input Parameters"}`
        fmt.Fprint(w, str)
        return
    }

    // Normal API handling
})

错误传播使用defer和recover

如果错误检测发生在ServeHTTP()之外,则可以使用defer和recover来传播将错误状态传递给主处理程序:

type params struct {
    // Parameter fields
}

func decodeParams(r *http.Request) (*params, error) {
    p := new(params)
    defer func() {
        if r := recover(); r != nil {
            log.Println(r)
            return
        }
    }()
    // Parameter decoding
    if !ok {
        panic(errors.New("Invalid Parameters"))
    }

    return p, nil
}

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    p, err := decodeParams(r)
    if err != nil {
        http.Error(w, `Invalid Input Parameters!`, http.StatusBadRequest)
        return
    }

    // Normal API handling
})

在这种方法中,defer 注册了一个清理函数,以确保不管函数返回还是panic,recover() 函数都会被执行。如果decodeParams检测到无效参数,它会发生恐慌,有效地从ServeHTTP()返回错误并允许它返回错误消息。

以上是如何在 Go 中优雅地处理和终止 HTTP 请求?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
与GO接口键入断言和类型开关与GO接口键入断言和类型开关May 02, 2025 am 12:20 AM

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

使用errors.is和错误。使用errors.is和错误。May 02, 2025 am 12:11 AM

Go语言的错误处理通过errors.Is和errors.As函数变得更加灵活和可读。1.errors.Is用于检查错误是否与指定错误相同,适用于错误链的处理。2.errors.As不仅能检查错误类型,还能将错误转换为具体类型,方便提取错误信息。使用这些函数可以简化错误处理逻辑,但需注意错误链的正确传递和避免过度依赖以防代码复杂化。

在GO中进行性能调整:优化您的应用程序在GO中进行性能调整:优化您的应用程序May 02, 2025 am 12:06 AM

tomakegoapplicationsRunfasterandMorefly,useProflingTools,leverageConCurrency,andManageMoryfectily.1)usepprofforcpuorforcpuandmemoryproflingtoidentifybottlenecks.2)upitizegorizegoroutizegoroutinesandchannelstoparalletaparelalyizetasksandimproverperformance.3)

GO的未来:趋势和发展GO的未来:趋势和发展May 02, 2025 am 12:01 AM

go'sfutureisbrightwithtrendslikeMprikeMprikeTooling,仿制药,云 - 纳蒂维德象,performanceEnhancements,andwebassemblyIntegration,butchallengeSinclainSinClainSinClainSiNgeNingsImpliCityInsImplicityAndimimprovingingRornhandRornrorlling。

了解Goroutines:深入研究GO的并发了解Goroutines:深入研究GO的并发May 01, 2025 am 12:18 AM

goroutinesarefunctionsormethodsthatruncurranceingo,启用效率和灯威量。1)shememanagedbodo'sruntimemultimusingmultiplexing,允许千sstorunonfewerosthreads.2)goroutinessimproverentimensImproutinesImproutinesImproveranceThroutinesImproveranceThrountinesimproveranceThroundinesImproveranceThroughEasySytaskParallowalizationAndeff

了解GO中的初始功能:目的和用法了解GO中的初始功能:目的和用法May 01, 2025 am 12:16 AM

purposeoftheInitfunctionoIsistoInitializeVariables,setUpConfigurations,orperformneccesSetarySetupBeforEtheMainFunctionExeCutes.useInitby.UseInitby:1)placingitinyourcodetorunautoamenationally oneraty oneraty oneraty on inity in ofideShortAndAndAndAndForemain,2)keepitiTshortAntAndFocusedonSimImimpletasks,3)

了解GO界面:综合指南了解GO界面:综合指南May 01, 2025 am 12:13 AM

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

从恐慌中恢复:何时以及如何使用recover()从恐慌中恢复:何时以及如何使用recover()May 01, 2025 am 12:04 AM

在Go中使用recover()函数可以从panic中恢复。具体方法是:1)在defer函数中使用recover()捕获panic,避免程序崩溃;2)记录详细的错误信息以便调试;3)根据具体情况决定是否恢复程序执行;4)谨慎使用,以免影响性能。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具