1

Is there an way to reject/block an request in go net/http "listenandserver"? In my case I want that only requests with useragent "test 1.0" are allowed. Everything else will be blocked.
"I also want to make an rate limit. ex: (If requests per second from same IP gets over 50 R/S over second block for 1h...)" I can do this but as I said I dont know how to block the request.

package main

import (
    "net/http"
)

func handle(w http.ResponseWriter, r *http.Request) {
    if r.UserAgent() == "test/1.0" {
        //Allow
    } else {
        //Block request
    }
}

func main() {
    http.HandleFunc("/", handle)
    http.ListenAndServe(":8080", nil)

}

1 Answer 1

2

There are a couple of options. The first is to return an error response:

func handle(w http.ResponseWriter, r *http.Request) {
    if r.UserAgent() == "test/1.0" {
        //Allow
    } else {
        http.Error(w, "forbidden", http.StatusForbidden)
        return
    }
}

The second is to hijack the the connection from the server and rudely close the connection:

func handle(w http.ResponseWriter, r *http.Request) {
    if r.UserAgent() == "test/1.0" {
        //Allow
    } else {
        if h, ok := w.(http.Hijacker); ok {
            c, _, err := h.Hijack()
            if err != nil {
                c.Close()
                return
            }
        }
        // fallback to error response
        http.Error(w, "forbidden", http.StatusForbidden)
        return
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.