为了账号安全,请及时绑定邮箱和手机立即绑定

Golang net/http Backend blocking requests

Golang net/http Backend blocking requests

Go
人到中年有点甜 2022-08-24 19:01:18
有没有办法在go net/http“listenandserver”中拒绝/阻止请求?在我的情况下,我希望只允许具有useragent“test 1.0”的请求。其他所有内容都将被阻止。“我还想制定一个速率限制。例如:(如果来自同一IP的请求每秒超过50 R / S超过第二个块1小时...)”我可以这样做,但正如我所说,我不知道如何阻止请求。package mainimport (    "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 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

有几种选择。第一种是返回错误响应:


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

    if r.UserAgent() == "test/1.0" {

        //Allow

    } else {

        http.Error(w, "forbidden", http.StatusForbidden)

        return

    }

}

第二种是从服务器劫持连接并粗鲁地关闭连接:


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

    }

}


查看完整回答
反对 回复 2022-08-24
  • 1 回答
  • 0 关注
  • 96 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号