handler.go 1.4 KB
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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
package admin

import (
	"fmt"
	"net/http"

	"github.com/eolinker/goku-api-gateway/module"
)

var (
	handler = &tHandler{
		serveMux: http.NewServeMux(),
		modules:  make(map[string]*HandlerItem),
	}
)

type tHandler struct {
	serveMux *http.ServeMux
	modules  map[string]*HandlerItem
}

//HandlerItem handlerItem
type HandlerItem struct {
	isOpen  bool
	handler http.Handler
	name    string
}

func (ht *HandlerItem) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if !ht.isOpen {
		w.WriteHeader(404)
		w.Write([]byte("404"))
		return
	}
	ht.handler.ServeHTTP(w, r)
}

func (hd *tHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if hd.serveMux == nil {
		w.WriteHeader(404)
		return
	}

	hd.serveMux.ServeHTTP(w, r)
}
func (hd *tHandler) Add(name string, pattern string, h http.Handler) {
	if _, has := hd.modules[pattern]; has {

		panic(fmt.Sprint("duplicate pattern:", pattern, " for module:", name))

		return
	}
	isOpen := module.IsOpen(name)

	ht := &HandlerItem{
		isOpen:  isOpen,
		handler: h,
		name:    name,
	}
	hd.modules[pattern] = ht
	hd.serveMux.Handle(pattern, ht)
}
func (hd *tHandler) Refresh() {
	for _, ht := range hd.modules {
		ht.isOpen = module.IsOpen(ht.name)
	}
}

//Handler handler
func Handler() http.Handler {
	return handler
}

Y
Your Name 已提交
74
//Add( add
Y
Your Name 已提交
75 76 77 78 79 80 81 82
func Add(name string, pattern string, h http.Handler) {
	handler.Add(name, pattern, h)
}

//Refresh refresh
func Refresh() {
	handler.Refresh()
}