在go中设置http处理程序

时间:2014-08-26 18:13:52

标签: http go handler

我正在跟随之旅,其中一个练习要求我建立一对http的处理程序。 这是代码:

    package main

import (
    "fmt"
    "net/http"
)

type String string

type Struct struct {
  Greeting string
  Punct string
  Who string

}

func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request){

    fmt.Fprint(w, s)

}
func (s *Struct) ServeHTTP(w http.ResponseWriter, r *http.Request){
  fmt.Fprint(w, "This is a struct. Yey!")
}

func main() {
    // your http.Handle calls here
    http.ListenAndServe("localhost:4000", nil)
    http.Handle("/string", String("I'm a frayed knot"))
    http.Handle("/struct", &Struct{"Hello",":","Gophers!"})
}

代码编译&运行得很好但是我不确定为什么当我导航到localhost:4000/stringlocalhost:4000/struct时,我得到的是来自默认http处理程序的404错误。

我在这里错过了一步还是?

2 个答案:

答案 0 :(得分:3)

您的代码停在ListenAndServe,即阻止。 (顺便说一句,如果ListenAndServe没有阻止,main将返回并且该过程将退出)

在此之前注册处理程序。

答案 1 :(得分:1)

更改main
func main() {
    // your http.Handle calls here
    http.ListenAndServe("localhost:4000", nil)
    http.Handle("/string", String("I'm a frayed knot"))
    http.Handle("/struct", &Struct{"Hello",":","Gophers!"})
}

func main() {
    http.Handle("/string", String("I'm a frayed knot"))
    http.Handle("/struct", &Struct{"Hello",":","Gophers!"})
    // your http.Handle calls here
    http.ListenAndServe("localhost:4000", nil)
}

http.ListenAndServe阻止,直到您终止该程序。

通常会添加退出值的日志:

log.Fatal(http.ListenAndServe(...))