在go中设置http处理程序

在go中设置http处理程序

问题描述:

I was following the go tour and one of the exercises asked me to build a couple http handlers. Here is the code:

    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!"})
}

The code compiles & runs just fine however I am not sure why when I navigate to localhost:4000/string or localhost:4000/struct all I get is a 404 error from the default http handler.

Am I missing a step here or?

Your code stops at ListenAndServe, which is blocking. (BTW, if ListenAndServe didn't block, main would return and the process would exit)

Register the handlers before that.

Change main from

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!"})
}

to

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 blocks until you terminate the program.

is common to add a log of the exit value:

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