Home > OS >  Is there a way to drop an http connection in golang without sending anything to client?
Is there a way to drop an http connection in golang without sending anything to client?

Time:05-25

In certain circumstances I do not want to respond anything to client, as if there were nothing responding in a certain port, as if the port were not in use.

Schematically:

func handleClient(w http.ResponseWriter, r *http.Request) {

    if ( **** condition **** ) {
        // Drop connection without sending anything to client
    } else {
        // Normal response
    }
    
}

I will appreciate any help or clue to afford it.

CodePudding user response:

You can hijack the connection to access the underlying tcp connection. It's supported by the standard http server in golang.

Below is the example from the documentation.
Instead of doing defer conn.Close() like in this example, you could call conn.Close() directly and return, this will drop the connection.

Keep in mind that at this point the connection has already been accepted. If you want to not even accept the connection, you'll need to implement a custom tcp listener that routes the traffic to your http server conditionally. You'll have to also consider what your condition will be. Or example, do you need to read anything from the http request in order to determine the outcome of your condition ?

http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) {
        hj, ok := w.(http.Hijacker)
        if !ok {
            http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
            return
        }
        conn, bufrw, err := hj.Hijack()
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        // Don't forget to close the connection:
        defer conn.Close()
        bufrw.WriteString("Now we're speaking raw TCP. Say hi: ")
        bufrw.Flush()
        s, err := bufrw.ReadString('\n')
        if err != nil {
            log.Printf("error reading string: %v", err)
            return
        }
        fmt.Fprintf(bufrw, "You said: %q\nBye.\n", s)
        bufrw.Flush()
    })

Full docs: https://pkg.go.dev/net/http#Hijacker

CodePudding user response:

just return inside if condition

func handleClient(w http.ResponseWriter, r *http.Request) {

    if ( **** condition **** ) {
        // Drop connection without sending anything to client
        return
    }
    
    // Normal response
}
  •  Tags:  
  • go
  • Related