Fragment Description:



ListenAndServe starts an HTTP server with a given address and handler.
The handler is usually nil, which means to use DefaultServeMux.
Handle and HandleFunc add handlers to DefaultServeMux

ServeHTTP

Last update, on 2015, Fri 9 Oct, 16:15:37

/* ... <== see fragment description ... */

package main

import (
    "fmt"
    "net/http"
)

// both type implements ServeHTTP
type (
    String string
    Struct struct {
        Greeting string
        Punct    string
        Who      string
    }
)

// sign: func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)
// where ServeMux is an HTTP request multiplexer.
// It matches the URL of each incoming request against a list of registered
// patterns and calls the handler for the pattern that most closely matches
// the URL.
func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "%s", s)
}
func (s *Struct) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "%s%s %s", s.Greeting, s.Punct, s.Who)
}
func main() {
    // http.Handle calls
    http.Handle("/string", String("I'm a frayed knot."))
    http.Handle("/struct", &Struct{
        Greeting: "Hello Struct",
        Punct:    ",",
        Who:      "World!",
    })
    http.Handle("/", &Struct{"Hello /", ",", "World!"})
    // ListenAndServe starts an HTTP server
    fmt.Println("Listening localhost:4000...")
    http.ListenAndServe("localhost:4000", nil)
}



Comments