package main
import (
"errors"
"net/http"
"strings"
)
type Handler1 struct {
}
type Handler2 struct {
}
type Handler3 struct {
}
func (h * Handler1) ServeHTTP(w http.ResponseWriter, r * http.Request) {
msg := "欢迎访问此网站1"
w.Write([]byte(msg))
}
func (h * Handler2) ServeHTTP(w http.ResponseWriter, r * http.Request) {
msg := "欢迎访问此网站2"
w.Write([]byte(msg))
}
func (h * Handler3) ServeHTTP(w http.ResponseWriter, r * http.Request) {
msg := "欢迎访问此网站3"
w.Write([]byte(msg))
}
type HandlerRoot struct {
http.ServeMux
hm map[string]http.Handler
}
func (h * HandlerRoot) MapHandler(path string, handler http.Handler) error {
if path == "" {
return errors.New("url不能为空")
}
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
if _, isExist := h.hm[path];isExist {
return errors.New("此url已经存在")
}
if h.hm == nil {
h.hm = make(map[string]http.Handler)
}
h.hm[path] = handler
return nil
}
func a(w http.ResponseWriter, r *http.Request) {
msg := "欢迎访问此网站1"
w.Write([]byte(msg))
}
func b(w http.ResponseWriter, r *http.Request) {
msg := "欢迎访问此网站2"
w.Write([]byte(msg))
}
func c(w http.ResponseWriter, r *http.Request) {
msg := "欢迎访问此网站3"
w.Write([]byte(msg))
}
func main() {
http.HandleFunc("/", a)
http.HandleFunc("/b", b)
http.HandleFunc("/c", c)
http.ListenAndServe("localhost:8080", nil)
}