doujun1495 2019-09-03 17:39
浏览 438
已采纳

在go中停止处理http请求

I'm trying to rewrite a small node-api in golang and there I found that the internal error doesn't stop the processing of the requests. Is there a nice way to end the processing?

I've tried different things like making a error-object and using panic(err) to exit the processing but I think there are better ways.

I expected a function which stops the processing of the request and throws an 500-error and maybe logs a thing or two.

The code-sample is like this:

package main

import (
    "fmt"
    "net/http"
    "strings"
)

func main() {
    http.HandleFunc("/ping/", ping)
    err := http.ListenAndServe(":8080", nil)
    checkErr(err)
}

func ping(w http.ResponseWriter, req *http.Request) {
    w.Write([]byte("pong
"))
    urlPath := req.URL.Path
    rest := strings.TrimPrefix(urlPath, "/ping/")
    testRest(w, rest)
}

func testRest(w http.ResponseWriter, rest string) {
    if rest == "abc" {
        http.Error(w, "The go-routine should stop here", 500)
    }
    fmt.Print("This shouldn't be printed")
}

func checkErr(err error) {
    if err != nil {
        panic(err)
    }
}

And I call it like that:

curl --url http://127.0.0.1:8080/ping/abc
  • 写回答

2条回答 默认 最新

  • dreamfly2016 2019-09-05 13:13
    关注

    There is no trick to it. When you want your handler function to stop doing things, just return from the function:

    func testRest(w http.ResponseWriter, rest string) {
        if rest == "abc" {
            http.Error(w, "The go-routine should stop here", 500)
            return
        }
        fmt.Print("This shouldn't be printed")
    }
    

    If you want to log something, log something:

    func testRest(w http.ResponseWriter, rest string) {
        if rest == "abc" {
            http.Error(w, "The go-routine should stop here", 500)
            log.Println("something bad happened")
            return
        }
        fmt.Print("This shouldn't be printed")
    }
    

    That's all there is to it. When you say "internal error doesn't stop the processing of the requests" it seems maybe you're thinking there's a lot more magic happening, but in Go there's very little magic. http.Error writes an error response back to the client. That's all. It has not way to "stop" anything; it just writes a status code and body to the client connection and then returns. After it returns, you have the opportunity to do more things in the calling code, but if you just want your function to return, then just return. Returning from the handler is what "stops processing the request" - your code is what's processing the request, you're in complete control.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1