我如何 http.ListenAndServe "/"并没有响应每条路径? [英] How do I http.ListenAndServe "/" and not have it respond to every path?

查看:67
本文介绍了我如何 http.ListenAndServe "/"并没有响应每条路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个小型 golang 服务器中有以下代码:

I have the following code in a small golang server:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {})

基本上允许您访问服务器的根目录而不会发生任何可怕的事情.

Basically allowing you to hit the root of the server without anything scary happening.

问题是您也可以点击 /foo/bar/blah... 并且它仍然有效.我不想要的.

The issue is that you can also hit /foo/bar/blah... and it still works. Which I don't want.

我如何明确地将其限制在我所说的范围内?

How can I explicitly restrict it to what I say?

推荐答案

将以下代码添加到处理程序的开头:

Add the following code to the beginning of your handler:

if r.URL.Path != "/" {
     http.NotFound(w, r)
     return
}

这篇关于我如何 http.ListenAndServe "/"并没有响应每条路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆