Skip to content

Instantly share code, notes, and snippets.

@aizatto
Created May 31, 2013 14:21
Show Gist options
  • Save aizatto/5685299 to your computer and use it in GitHub Desktop.
Save aizatto/5685299 to your computer and use it in GitHub Desktop.
http://tour.golang.org/#57 A Tour of Go Exercise: HTTP Handlers Implement the following types and define ServeHTTP methods on them. Register them to handle specific paths in your web server. type String string type Struct struct { Greeting string Punct string Who string } For example, you should be able to register handlers using: http.Handle("/…
package main
import (
"fmt"
"net/http"
)
type String string
func (s String) ServeHTTP(
w http.ResponseWriter,
r *http.Request) {
fmt.Fprint(w, s)
}
type Struct struct {
Greeting string
Punct string
Who string
}
func (s Struct) ServeHTTP(
w http.ResponseWriter,
r *http.Request) {
fmt.Fprint(w, s.Greeting, s.Punct, s.Who)
}
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!"})
}
@takashi
Copy link

takashi commented Apr 9, 2014

not works well, maybe fix with fixing order of main func lines.

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

@andradei
Copy link

andradei commented Mar 6, 2015

It seems that, for this exercise, you can achieve the same result with:

func (s Struct) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, s)
}

Just like the implementation on String

@komuw
Copy link

komuw commented Jul 8, 2015

@aizatto for your solution to work, you need to change your main function to:

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

otherwise, trying to navigate to http://localhost:4000/string you will get a 'Not Found' error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment