在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

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.

I'd use cancellation by using the context library native in Go.

an example of how you could active that: https://play.golang.org/p/qF7aQ1DP3vM

Here a nice artice about the topic: https://medium.com/the-software-firehose/canceling-requests-in-go-using-context-b4b28a118da8

Edit

It's important to keep in mind that this would be a solution for client requests only. If you want to cancel requests from server a different approach might be necessary.