简体   繁体   中英

Setting up a http handler in go

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(...))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM