router.go 5.1 KB
Newer Older
Y
Your Name 已提交
1 2 3 4
package gateway

import (
	"errors"
Y
Your Name 已提交
5
	"fmt"
Y
Your Name 已提交
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
	"net/http"
	"reflect"
	"strings"

	"github.com/eolinker/goku-api-gateway/config"
	"github.com/eolinker/goku-api-gateway/goku-service/balance"
	"github.com/eolinker/goku-api-gateway/goku-service/discovery"
	"github.com/eolinker/goku-api-gateway/node/gateway/application"
	plugin_executor "github.com/eolinker/goku-api-gateway/node/gateway/plugin-executor"
	plugin_loader "github.com/eolinker/goku-api-gateway/node/plugin-loader"
	"github.com/eolinker/goku-api-gateway/node/router"
)

var (
	errorConfig = errors.New("config is error")
)

//Parse 解析
func Parse(config *config.GokuConfig, factory router.Factory) (http.Handler, error) {

	if config == nil {
		return nil, errorConfig
	}

	f := genFactory(config, factory)

	return &HTTPHandler{router: f.create()}, nil
}

type _RootFactory struct {
	orgCfg        *config.GokuConfig
	beforePlugin  []plugin_executor.Executor
	gBefores      []plugin_executor.Executor
	gAccesses     []plugin_executor.Executor
	gProxies      []plugin_executor.Executor
	apis          map[int]*config.APIContent
	appFactory    *application.Factory
	routerFactory router.Factory
	cluster       string

	authPlugin map[string]string
}

func (f *_RootFactory) create() *Before {
	beforeRouter := &Before{
		pluginBefor:       f.beforePlugin,
		pluginGlobalBefor: f.gBefores,
		strategies:        f.createStrategy(),
		anonymousStrategy: f.orgCfg.AnonymousStrategyID,
	}

	return beforeRouter
}
func (f *_RootFactory) createStrategy() map[string]*Strategy {
	strategys := make(map[string]*Strategy)

	for _, cfg := range f.orgCfg.Strategy {

		strategyRouter := f.genStrategy(cfg)
		strategys[cfg.ID] = strategyRouter
	}

	return strategys
}

// 构造策略
func (f *_RootFactory) genStrategy(cfg *config.StrategyConfig) *Strategy {
Y
Your Name 已提交
73
	_, accesses, proxies := genPlugins(cfg.Plugins, f.cluster, cfg.ID, 0)
Y
Your Name 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

	s := &Strategy{
		ID:     cfg.ID,
		Name:   cfg.Name,
		Enable: cfg.Enable,

		accessPlugin:       accesses,
		globalAccessPlugin: f.gAccesses,
		authPlugin:         make(map[string]plugin_executor.Executor),
		isNeedAuth:         false,
	}
	if !s.Enable {
		return s
	}
	s.apiRouter = f.routerFactory.New()
	s.apiRouter.AddNotFound(s.HandlerAPINotFound)
	for authKey, authCfg := range cfg.AUTH {
		s.isNeedAuth = true
		pluginName, has := f.authPlugin[authKey]
		if has {
			pluginFactory, e := plugin_loader.LoadPlugin(pluginName)
			if e != nil {
				continue
			}
			pluginObj, err := pluginFactory.Create(authCfg, f.cluster, "", s.ID, 0)
			if err != nil {
				continue
			}

			if pluginObj.Access != nil && !reflect.ValueOf(pluginObj.Access).IsNil() {
Y
Your Name 已提交
104 105 106
				if cfg.ID == "68YAY7" {
					fmt.Println(authKey, pluginName)
				}
Y
Your Name 已提交
107 108 109 110
				s.authPlugin[authKey] = plugin_executor.NewAccessExecutor(&config.PluginConfig{
					Name:   pluginName,
					IsStop: true,
					Config: authCfg,
Y
Your Name 已提交
111
					IsAuth: true,
Y
Your Name 已提交
112 113 114 115 116 117 118 119
				}, pluginObj.Access)
			}
		}
	}

	factory := newAPIFactory(f, s.ID)
	for _, apiCfg := range cfg.APIS {

Y
Your Name 已提交
120
		iRouter, apiContent := factory.genAPIRouter(apiCfg, proxies)
Y
Your Name 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
		if iRouter == nil {
			continue
		}
		for _, method := range apiContent.Methods {

			s.apiRouter.AddRouter(strings.ToUpper(method), apiContent.RequestURL, iRouter)
		}
	}

	return s
}

type _ApiFactory struct {
	root       *_RootFactory
	strategyID string
}

func newAPIFactory(root *_RootFactory, strategyID string) *_ApiFactory {
	return &_ApiFactory{
		root:       root,
		strategyID: strategyID,
	}
}
Y
Your Name 已提交
144
func (f *_ApiFactory) genAPIRouter(cfg *config.APIOfStrategy, proxies []plugin_executor.Executor) (router.IRouter, *config.APIContent) {
Y
Your Name 已提交
145 146 147 148 149 150 151 152 153 154 155

	apiContend, has := f.root.apis[cfg.ID]
	if !has {
		return nil, nil
	}

	app, err := f.root.appFactory.GenApplication(cfg)
	if err != nil {
		return nil, nil
	}
	_, pluginAccesses, pluginProxies := genPlugins(cfg.Plugins, f.root.cluster, f.strategyID, cfg.ID)
Y
Your Name 已提交
156 157 158
	pro := make([]plugin_executor.Executor, 0, len(proxies)+len(pluginProxies))
	pro = append(pro, proxies...)
	pro = append(pro, pluginProxies...)
Y
Your Name 已提交
159 160 161

	return &API{
		strategyID:          f.strategyID,
Y
Your Name 已提交
162
		apiID:               cfg.ID,
Y
Your Name 已提交
163 164
		app:                 app,
		pluginAccess:        pluginAccesses,
Y
Your Name 已提交
165
		pluginProxies:       pro,
Y
Your Name 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
		pluginAccessGlobal:  f.root.gAccesses,
		pluginProxiesGlobal: f.root.gProxies,
	}, apiContend
}

func genFactory(cfg *config.GokuConfig, factory router.Factory) *_RootFactory {

	discovery.ResetAllServiceConfig(cfg.DiscoverConfig)
	balance.ResetBalances(cfg.Balance)

	beforePlugin := genBeforPlugin(cfg.Plugins.BeforePlugins, cfg.Cluster)

	gBefores, gAccesses, gProxies := genPlugins(cfg.Plugins.GlobalPlugins, cfg.Cluster, "", 0)
	apis := toMap(cfg.APIS)
	return &_RootFactory{
		beforePlugin:  beforePlugin,
		gBefores:      gBefores,
		gAccesses:     gAccesses,
		gProxies:      gProxies,
		appFactory:    application.NewFactory(apis),
		apis:          apis,
		routerFactory: factory,
		cluster:       cfg.Cluster,
		orgCfg:        cfg,
		authPlugin:    cfg.AuthPlugin,
	}
}

func toMap(cfgs []*config.APIContent) map[int]*config.APIContent {
	m := make(map[int]*config.APIContent)
	for _, cfg := range cfgs {
Y
Your Name 已提交
197 198 199
		//if cfg.ID == 1880 {
		//	fmt.Println(cfg)
		//}
Y
Your Name 已提交
200 201 202 203
		m[cfg.ID] = cfg
	}
	return m
}