Bula
Bula

Reputation: 2792

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?

Upvotes: 0

Views: 920

Answers (2)

fabmilo
fabmilo

Reputation: 48330

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

Upvotes: 1

Mr_Pink
Mr_Pink

Reputation: 109438

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.

Upvotes: 3

Related Questions