Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop processing of http request in go

Tags:

rest

go

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\n"))
    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
like image 451
Luca R Avatar asked Oct 31 '25 06:10

Luca R


1 Answers

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.

like image 51
Adrian Avatar answered Nov 03 '25 03:11

Adrian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!