handler.go 893 字节
Newer Older
Y
Your Name 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
package goku_handler

import (
	"fmt"
	"net/http"
	"strings"
)

//GokuHandler gokuHandler
type GokuHandler interface {
	Handlers(factory *AccountHandlerFactory) map[string]http.Handler
}

//GokuServer gokuServer
type GokuServer struct {
	factory *AccountHandlerFactory
	mux     *http.ServeMux
}

func (s *GokuServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	s.mux.ServeHTTP(w, r)
}

//NewGokuServer new gokuServer
func NewGokuServer(factory *AccountHandlerFactory) *GokuServer {
	return &GokuServer{
		factory: factory,
		mux:     http.NewServeMux(),
	}
}

//Add add
func (s *GokuServer) Add(pre string, handler GokuHandler) {
	handlers := handler.Handlers(s.factory)

	for sub, h := range handlers {

		path := join(pre, sub)
		s.mux.Handle(path, h)
	}
}

func join(pre, sub string) string {

	return fmt.Sprint(strings.TrimSuffix(pre, "/"), "/", strings.TrimPrefix(sub, "/"))

}