英文:
about golang HandlerFunc. I expected 404 not found but
问题
这是我的代码:
package main
import "encoding/json"
import "net/http"
import "time"
import "fmt"
import "os"
type Profile struct {
Name string
Hobbies []string
}
func main() {
http.HandleFunc("/", rootFunc) //routeSet()
err := http.ListenAndServe(":3000", nil)
checkError(err)
}
func checkError(err error) {
if err != nil {
fmt.Println("Fatal Error", err.Error())
os.Exit(1)
}
}
func rootFunc(w http.ResponseWriter, r *http.Request) {
//fmt.Println("Request url : " + r.RequestURI)
userProfile := make(chan Profile)
go goFun(userProfile, w, r)
profile := <-userProfile
js, err := json.Marshal(profile)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
func goFun(u chan Profile, w http.ResponseWriter, r *http.Request) {
// time.Sleep(1 * time.Second)
u <- Profile{"Alex", []string{r.RequestURI, "programming"}}
}
我通过Postman发送了http://localhost:3000/hello
,并收到了以下响应:
{
"Name": "Alex",
"Hobbies": [
"/hello",
"programming"
]
}
我预期会收到404 Not Found,因为我只为"/"使用了HandleFunc(),但我收到了正常的结果。
环境:
Go 1.6
Mac OS X
英文:
this is my code
package main
import "encoding/json"
import "net/http"
import "time"
import "fmt"
import "os"
type Profile struct {
Name string
Hobbies []string
}
func main() {
http.HandleFunc("/", rootFunc)//routeSet()
err :=http.ListenAndServe(":3000", nil)
checkError(err)
}
func checkError(err error) {
if err != nil {
fmt.Println("Fatal Error", err.Error())
os.Exit(1)
}
}
func rootFunc(w http.ResponseWriter, r *http.Request) {
//fmt.Println("Request url : " + r.RequestURI)
userProfile := make(chan Profile)
go goFun(userProfile, w, r)
profile := <-userProfile
js, err := json.Marshal(profile)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
func goFun(u chan Profile, w http.ResponseWriter, r *http.Request) {
// time.Sleep(1 * time.Second)
u <- Profile{"Alex", []string{r.RequestURI, "programming"}}
}
and I send http://localhost:3000/hello by postman
and I recieve
{
"Name": "Alex",
"Hobbies": [
"/hello",
"programming"
]
}
I expected 404 not found, because I use HandleFunc() only for "/"
but i received normal result.
...........................
env.
go 1.6
max osx
...........................
答案1
得分: 3
"/"
是一个根节点的子树,基本上可以匹配任何内容。请参考 https://golang.org/pkg/net/http/#ServeMux (在做任何假设之前,请始终查阅文档)。
英文:
"/"
is a rooted subtree and matches basically everything. See https://golang.org/pkg/net/http/#ServeMux . (Always consult the documentation before making any assumptions.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论