dsz90288 2016-03-14 08:33
浏览 87

关于golang HandlerFunc。 我预计找不到404,但

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条回答 默认 最新

  • duanju8308 2016-03-14 08:42
    关注

    "/" is a rooted subtree and matches basically everything. See https://golang.org/pkg/net/http/#ServeMux . (Always consult the documentation before making any assumptions.)

    评论

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私