// RouterFromConfig setup a chi.Mux router from a json configuration.
194940
func RouterFromConfig(config json.RawMessage, silent bool) *chi.Mux {
	r := chi.NewRouter()
	if !silent {
		r.Use(middleware.Logger)
	}

	services := []Definition{}
	if err := json.Unmarshal(config, &services); err != nil {
		log.Fatal(err)
	} else if len(services) == 0 {
		log.Fatal("configuration should define at least 1 url.")
	}

	for _, srv := range services {
		if srv.Deleter == nil &&
			srv.ReaderPipe == nil &&
			srv.WriterPipe == nil {
			log.Fatalf("service '%s' should define at least a writer, reader or deleter.", srv.URL)
		}
		if !silent {
			log.Printf("registering service with url '%s'", srv.URL)
		}

		SetHandler(r, srv)
	}
	return r
}
895589
func routersFor(route *route, routers []*Router) []*Router {
	routers = routers[:0]
	curRouter := route.Router
	for curRouter != nil {
		routers = append(routers, curRouter)
		curRouter = curRouter.parent
	}

	// Reverse the slice
	s := 0
	e := len(routers) - 1
	for s < e {
		routers[s], routers[e] = routers[e], routers[s]
		s++
		e--
	}

	return routers
}
1120067
func NewRouter(f *Fibre) *Router {
	return &Router{
		fibre:  f,
		routes: make(map[string][]*Route),
	}
}
1089463
func NetworkConfigFromInterfaceInfo(interfaceInfos []network.InterfaceInfo) []params.NetworkConfig {
	result := make([]params.NetworkConfig, len(interfaceInfos))
	for i, v := range interfaceInfos {
		var dnsServers []string
		for _, nameserver := range v.DNSServers {
			dnsServers = append(dnsServers, nameserver.Value)
		}
		routes := make([]params.NetworkRoute, len(v.Routes))
		for j, route := range v.Routes {
			routes[j] = params.NetworkRoute{
				DestinationCIDR: route.DestinationCIDR,
				GatewayIP:       route.GatewayIP,
				Metric:          route.Metric,
			}
		}
		result[i] = params.NetworkConfig{
			DeviceIndex:         v.DeviceIndex,
			MACAddress:          v.MACAddress,
			CIDR:                v.CIDR,
			MTU:                 v.MTU,
			ProviderId:          string(v.ProviderId),
			ProviderSubnetId:    string(v.ProviderSubnetId),
			ProviderSpaceId:     string(v.ProviderSpaceId),
			ProviderVLANId:      string(v.ProviderVLANId),
			ProviderAddressId:   string(v.ProviderAddressId),
			VLANTag:             v.VLANTag,
			InterfaceName:       v.InterfaceName,
			ParentInterfaceName: v.ParentInterfaceName,
			InterfaceType:       string(v.InterfaceType),
			Disabled:            v.Disabled,
			NoAutoStart:         v.NoAutoStart,
			ConfigType:          string(v.ConfigType),
			Address:             v.Address.Value,
			DNSServers:          dnsServers,
			DNSSearchDomains:    v.DNSSearchDomains,
			GatewayAddress:      v.GatewayAddress.Value,
			Routes:              routes,
			IsDefaultGateway:    v.IsDefaultGateway,
		}
	}
	return result
}
846598
func (s *Action) SetRedirectConfig(v *RedirectActionConfig) *Action {
	s.RedirectConfig = v
	return s
}
436506
func defaultConfig(transportFn func() *http.Transport) *Config {
	config := &Config{
		Address:   "127.0.0.1:8500",
		Scheme:    "http",
		Transport: transportFn(),
	}

	if addr := os.Getenv(HTTPAddrEnvName); addr != "" {
		config.Address = addr
	}

	if tokenFile := os.Getenv(HTTPTokenFileEnvName); tokenFile != "" {
		config.TokenFile = tokenFile
	}

	if token := os.Getenv(HTTPTokenEnvName); token != "" {
		config.Token = token
	}

	if auth := os.Getenv(HTTPAuthEnvName); auth != "" {
		var username, password string
		if strings.Contains(auth, ":") {
			split := strings.SplitN(auth, ":", 2)
			username = split[0]
			password = split[1]
		} else {
			username = auth
		}

		config.HttpAuth = &HttpBasicAuth{
			Username: username,
			Password: password,
		}
	}

	if ssl := os.Getenv(HTTPSSLEnvName); ssl != "" {
		enabled, err := strconv.ParseBool(ssl)
		if err != nil {
			log.Printf("[WARN] client: could not parse %s: %s", HTTPSSLEnvName, err)
		}

		if enabled {
			config.Scheme = "https"
		}
	}

	if v := os.Getenv(HTTPTLSServerName); v != "" {
		config.TLSConfig.Address = v
	}
	if v := os.Getenv(HTTPCAFile); v != "" {
		config.TLSConfig.CAFile = v
	}
	if v := os.Getenv(HTTPCAPath); v != "" {
		config.TLSConfig.CAPath = v
	}
	if v := os.Getenv(HTTPClientCert); v != "" {
		config.TLSConfig.CertFile = v
	}
	if v := os.Getenv(HTTPClientKey); v != "" {
		config.TLSConfig.KeyFile = v
	}
	if v := os.Getenv(HTTPSSLVerifyEnvName); v != "" {
		doVerify, err := strconv.ParseBool(v)
		if err != nil {
			log.Printf("[WARN] client: could not parse %s: %s", HTTPSSLVerifyEnvName, err)
		}
		if !doVerify {
			config.TLSConfig.InsecureSkipVerify = true
		}
	}

	return config
}
40153
func keyForConfig(blocIndex int, blocKeyIndex int) string {
	return fmt.Sprintf("%d:%d", blocIndex, blocKeyIndex)
}
529658
func (r *Router) MatcherFunc(f MatcherFunc) *Route {
	return r.NewRoute().MatcherFunc(f)
}
208311
func NewRouter() *Router {
	return &Router{
		routes:     map[HTTPMethod]map[string]http.HandlerFunc{},
		regexps:    map[HTTPMethod]map[*regexp.Regexp]http.HandlerFunc{},
		subrouters: []*Router{},
	}
}
826752
func ParseProxyConfig(m map[string]interface{}) (ProxyConfig, error) {
	var cfg ProxyConfig
	err := mapstructure.WeakDecode(m, &cfg)
	// Set defaults (even if error is returned)
	if cfg.Protocol == "" {
		cfg.Protocol = "tcp"
	} else {
		cfg.Protocol = strings.ToLower(cfg.Protocol)
	}
	if cfg.LocalConnectTimeoutMs < 1 {
		cfg.LocalConnectTimeoutMs = 5000
	}
	return cfg, err
}
182099
func NewConfigFromString(rootLogger *logrus.Logger, input []byte) Config {
	logger := rootLogger.WithFields(logrus.Fields{"prefix": "config"})
	return newConfigFromString(logger, input)
}
539022
func OptsFromPeerConfig(peerCfg *fab.PeerConfig) []options.Opt {

	opts := []options.Opt{
		WithHostOverride(getServerNameOverride(peerCfg)),
		WithFailFast(getFailFast(peerCfg)),
		WithKeepAliveParams(getKeepAliveOptions(peerCfg)),
		WithCertificate(peerCfg.TLSCACert),
	}
	if isInsecureAllowed(peerCfg) {
		opts = append(opts, WithInsecure())
	}

	return opts
}
1250423
func BuildRouterConfiguration(ctx context.Context, configuration *config.HTTPConfiguration, defaultRouterName string, defaultRuleTpl *template.Template, model interface{}) {
	if len(configuration.Routers) == 0 {
		if len(configuration.Services) > 1 {
			log.FromContext(ctx).Info("Could not create a router for the container: too many services")
		} else {
			configuration.Routers = make(map[string]*config.Router)
			configuration.Routers[defaultRouterName] = &config.Router{}
		}
	}

	for routerName, router := range configuration.Routers {
		loggerRouter := log.FromContext(ctx).WithField(log.RouterName, routerName)
		if len(router.Rule) == 0 {
			writer := &bytes.Buffer{}
			if err := defaultRuleTpl.Execute(writer, model); err != nil {
				loggerRouter.Errorf("Error while parsing default rule: %v", err)
				delete(configuration.Routers, routerName)
				continue
			}

			router.Rule = writer.String()
			if len(router.Rule) == 0 {
				loggerRouter.Error("Undefined rule")
				delete(configuration.Routers, routerName)
				continue
			}
		}

		if len(router.Service) == 0 {
			if len(configuration.Services) > 1 {
				delete(configuration.Routers, routerName)
				loggerRouter.
					Error("Could not define the service name for the router: too many services")
				continue
			}

			for serviceName := range configuration.Services {
				router.Service = serviceName
			}
		}
	}
}
795896
func ReattachConfigFromGoPlugin(plug *plugin.ReattachConfig) *ReattachConfig {
	if plug == nil {
		return nil
	}

	rc := &ReattachConfig{
		Protocol: string(plug.Protocol),
		Network:  plug.Addr.Network(),
		Addr:     plug.Addr.String(),
		Pid:      plug.Pid,
	}

	return rc
}
891706
func (f *MockInfraProvider) CreateOrdererFromConfig(cfg *fab.OrdererConfig) (fab.Orderer, error) {
	if f.customOrderer != nil {
		return f.customOrderer, nil
	}

	if cfg.URL != "" {
		return &MockOrderer{OrdererURL: cfg.URL}, nil
	}

	return &MockOrderer{}, nil
}
971513
func (f *MockInfraProvider) CreatePeerFromConfig(peerCfg *fab.NetworkPeer) (fab.Peer, error) {
	if peerCfg != nil {
		p := NewMockPeer(peerCfg.MSPID, peerCfg.URL)
		p.SetMSPID(peerCfg.MSPID)

		return p, nil
	}
	return &MockPeer{}, nil
}
1165217
func ReadConfigFromFile(path string) (*Config, error) {
	buffer, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	return ReadConfig(buffer)
}