Пример #1
0
// Router constructs the main Devd router that serves all requests
func (dd *Devd) Router(logger termlog.TermLog, templates *template.Template) (http.Handler, error) {
	mux := http.NewServeMux()
	hasGlobal := false

	ci := inject.CopyInject{}
	if dd.HasLivereload() {
		ci = livereload.Injector
	}

	for match, route := range dd.Routes {
		if match == "/" {
			hasGlobal = true
		}
		handler := dd.WrapHandler(
			logger,
			route.Endpoint.Handler(templates, ci),
		)
		handler = http.StripPrefix(route.Path, handler)
		mux.Handle(match, handler)
	}
	if dd.HasLivereload() {
		lr := livereload.NewServer("livereload", logger)
		mux.Handle(livereload.EndpointPath, lr)
		mux.Handle(livereload.ScriptPath, http.HandlerFunc(lr.ServeScript))
		if dd.LivereloadRoutes {
			err := WatchRoutes(dd.Routes, lr, dd.Excludes, logger)
			if err != nil {
				return nil, fmt.Errorf("Could not watch routes for livereload: %s", err)
			}
		}
		if len(dd.WatchPaths) > 0 {
			err := WatchPaths(dd.WatchPaths, dd.Excludes, lr, logger)
			if err != nil {
				return nil, fmt.Errorf("Could not watch path for livereload: %s", err)
			}
		}
		dd.lrserver = lr
	}
	if !hasGlobal {
		mux.Handle(
			"/",
			dd.WrapHandler(logger, HandleNotFound(templates)),
		)
	}
	var h = http.Handler(mux)
	if dd.Credentials != nil {
		h = httpauth.SimpleBasicAuth(
			dd.Credentials.username, dd.Credentials.password,
		)(h)
	}
	return hostPortStrip(h), nil
}
Пример #2
0
// Handler construc5ts the Devd handler
func (dd *Devd) Handler(logger termlog.Logger, templates *template.Template) (http.Handler, error) {
	mux := http.NewServeMux()
	for match, route := range dd.Routes {
		mux.Handle(match, dd.RouteHandler(logger, route, templates))
	}
	if dd.HasLivereload() {
		lr := livereload.NewServer("livereload", logger)
		mux.Handle(livereload.EndpointPath, lr)
		mux.Handle(livereload.ScriptPath, http.HandlerFunc(lr.ServeScript))
		if dd.LivereloadRoutes {
			err := WatchRoutes(dd.Routes, lr, dd.Excludes, logger)
			if err != nil {
				return nil, fmt.Errorf("Could not watch routes for livereload: %s", err)
			}
		}
		if len(dd.WatchPaths) > 0 {
			err := WatchPaths(dd.WatchPaths, dd.Excludes, lr, logger)
			if err != nil {
				return nil, fmt.Errorf("Could not watch path for livereload: %s", err)
			}
		}
	}
	return hostPortStrip(mux), nil
}
Пример #3
0
func main() {
	httpIP := kingpin.Flag("address", "Address to listen on").
		Short('A').
		Default("127.0.0.1").
		String()

	allInterfaces := kingpin.Flag("a", "Listen on all addresses").
		Short('a').
		Bool()

	certFile := kingpin.Flag("cert", "Certificate bundle file - enables TLS").
		Short('c').
		PlaceHolder("PATH").
		Default("").
		ExistingFile()

	throttleDownKbps := kingpin.Flag(
		"down",
		"Throttle downstream from the client to N kilobytes per second",
	).
		PlaceHolder("N").
		Short('d').
		Default("0").
		Int()

	logHeaders := kingpin.Flag("logheaders", "Log headers").
		Short('H').
		Default("false").
		Bool()

	ignoreHeaders := kingpin.Flag(
		"ignore",
		"Disable logging matching requests. Regexes are matched over 'host/path'",
	).
		Short('I').
		PlaceHolder("REGEX").
		Strings()

	livereloadRoutes := kingpin.Flag("livereload", "Enable livereload for static files").
		Short('l').
		Default("false").
		Bool()

	latency := kingpin.Flag("latency", "Add N milliseconds of round-trip latency").
		PlaceHolder("N").
		Short('n').
		Default("0").
		Int()

	openBrowser := kingpin.Flag("open", "Open browser window on startup").
		Short('o').
		Default("false").
		Bool()

	httpPort := kingpin.Flag(
		"port",
		"Port to listen on - if not specified, devd will auto-pick a sensible port",
	).
		Short('p').
		Int()

	enableTimer := kingpin.Flag("logtime", "Log timing").
		Short('T').
		Default("false").
		Bool()

	throttleUpKbps := kingpin.Flag(
		"up",
		"Throttle upstream from the client to N kilobytes per second",
	).
		PlaceHolder("N").
		Short('u').
		Default("0").
		Int()

	watch := kingpin.Flag("watch", "Watch path to trigger livereload").
		PlaceHolder("PATH").
		Short('w').
		Strings()

	debug := kingpin.Flag("debug", "Debugging for devd development").
		Default("false").
		Bool()

	excludes := kingpin.Flag("exclude", "Glob pattern for files to exclude from livereload.").
		PlaceHolder("PATTERN").
		Short('x').
		Strings()

	routes := kingpin.Arg(
		"route",
		`Routes have the following forms:
			[SUBDOMAIN]/<PATH>=<DIR>
			[SUBDOMAIN]/<PATH>=<URL>
			<DIR>
			<URL>
		`,
	).Required().Strings()

	kingpin.Version(version)

	kingpin.Parse()

	logger := termlog.NewLog()

	if *debug {
		logger.Enable("debug")
	}
	if *enableTimer {
		logger.Enable("timer")
	}
	if *throttleDownKbps == 0 {
		*throttleDownKbps = slowdown.MaxRate
	}
	if *throttleUpKbps == 0 {
		*throttleUpKbps = slowdown.MaxRate
	}

	if *allInterfaces {
		*httpIP = "0.0.0.0"
	}

	tlsEnabled := false
	if *certFile != "" {
		tlsEnabled = true
	}

	var hl net.Listener
	var err error
	if *httpPort > 0 {
		hl, err = net.Listen("tcp", fmt.Sprintf("%v:%d", *httpIP, *httpPort))
	} else {
		hl, err = pickPort(*httpIP, portLow, portHigh, tlsEnabled)
	}
	if err != nil {
		kingpin.Fatalf("Could not bind to port: %s", err)
		return
	}

	templates := ricetemp.MustMakeTemplates(rice.MustFindBox("templates"))
	if err != nil {
		kingpin.Fatalf("Error loading templates: %s", err)
		return
	}

	ignores := make([]*regexp.Regexp, 0, 0)
	for _, expr := range *ignoreHeaders {
		v, err := regexp.Compile(expr)
		if err != nil {
			kingpin.Fatalf("%s", err)
		}
		ignores = append(ignores, v)
	}

	routeColl := make(routeCollection)
	for _, s := range *routes {
		err := routeColl.Set(s)
		if err != nil {
			kingpin.FatalUsage("Invalid route specification: %s", err)
		}
	}

	mux := http.NewServeMux()
	var livereloadEnabled = false
	if *livereloadRoutes || len(*watch) > 0 {
		livereloadEnabled = true
	}

	for match, route := range routeColl {
		handler := devdHandler(
			logger,
			route,
			templates,
			*logHeaders,
			ignores,
			livereloadEnabled,
			*latency,
		)
		mux.Handle(match, http.StripPrefix(route.Path, handler))
	}

	lr := livereload.NewServer("livereload", logger)
	if livereloadEnabled {
		mux.Handle("/livereload", lr)
		mux.Handle("/livereload.js", http.HandlerFunc(lr.ServeScript))
	}
	if *livereloadRoutes {
		err = WatchRoutes(routeColl, lr)
		if err != nil {
			kingpin.Fatalf("Could not watch routes for livereload: %s", err)
		}
	}
	if len(*watch) > 0 {
		err = WatchPaths(*watch, *excludes, lr, logger)
		if err != nil {
			kingpin.Fatalf("Could not watch path for livereload: %s", err)
		}
	}

	var tlsConfig *tls.Config
	if *certFile != "" {
		tlsConfig, err = getTLSConfig(*certFile)
		if err != nil {
			kingpin.Fatalf("Could not load certs: %s", err)
			return
		}
		hl = tls.NewListener(hl, tlsConfig)
	}
	hl = slowdown.NewSlowListener(
		hl,
		float64(*throttleUpKbps)*1024,
		float64(*throttleDownKbps)*1024,
	)

	url := formatURL(tlsEnabled, *httpIP, hl.Addr().(*net.TCPAddr).Port)
	logger.Say("Listening on %s (%s)", url, hl.Addr().String())
	if *openBrowser {
		go func() {
			webbrowser.Open(url)
		}()
	}
	server := &http.Server{
		Addr:    hl.Addr().String(),
		Handler: hostPortStrip(mux),
	}
	err = server.Serve(hl)
	logger.Shout("Server stopped: %v", err)
}
Пример #4
0
// Serve starts the devd server
func (dd *Devd) Serve(logger termlog.Logger) error {
	templates, err := ricetemp.MakeTemplates(rice.MustFindBox("templates"))
	if err != nil {
		return fmt.Errorf("Error loading templates: %s", err)
	}

	ignores := make([]*regexp.Regexp, 0, 0)
	for _, expr := range dd.IgnoreLogs {
		v, err := regexp.Compile(expr)
		if err != nil {
			return fmt.Errorf("%s", err)
		}
		ignores = append(ignores, v)
	}

	routeColl := make(RouteCollection)
	for _, s := range dd.Routes {
		err := routeColl.Set(s)
		if err != nil {
			return fmt.Errorf("Invalid route specification: %s", err)
		}
	}

	mux := http.NewServeMux()
	for match, route := range routeColl {
		handler := dd.RouteHandler(logger, route, templates, ignores)
		mux.Handle(match, http.StripPrefix(route.Path, handler))
	}

	lr := livereload.NewServer("livereload", logger)
	if dd.LivereloadEnabled() {
		mux.Handle("/livereload", lr)
		mux.Handle("/livereload.js", http.HandlerFunc(lr.ServeScript))
	}
	if dd.LivereloadRoutes {
		err = WatchRoutes(routeColl, lr, dd.Excludes, logger)
		if err != nil {
			return fmt.Errorf("Could not watch routes for livereload: %s", err)
		}
	}
	if len(dd.Watch) > 0 {
		err = WatchPaths(dd.Watch, dd.Excludes, lr, logger)
		if err != nil {
			return fmt.Errorf("Could not watch path for livereload: %s", err)
		}
	}

	var hl net.Listener
	tlsEnabled := false
	if dd.CertFile != "" {
		tlsEnabled = true
	}
	if dd.Port > 0 {
		hl, err = net.Listen("tcp", fmt.Sprintf("%v:%d", dd.Address, dd.Port))
	} else {
		hl, err = pickPort(dd.Address, portLow, portHigh, tlsEnabled)
	}
	if err != nil {
		return fmt.Errorf("Could not bind to port: %s", err)
	}

	var tlsConfig *tls.Config
	if dd.CertFile != "" {
		tlsConfig, err = getTLSConfig(dd.CertFile)
		if err != nil {
			return fmt.Errorf("Could not load certs: %s", err)
		}
		hl = tls.NewListener(hl, tlsConfig)
	}
	hl = slowdown.NewSlowListener(hl, dd.UpKbps*1024, dd.DownKbps*1024)

	url := formatURL(tlsEnabled, dd.Address, hl.Addr().(*net.TCPAddr).Port)
	logger.Say("Listening on %s (%s)", url, hl.Addr().String())
	if dd.OpenBrowser {
		go func() {
			webbrowser.Open(url)
		}()
	}
	server := &http.Server{
		Addr:    hl.Addr().String(),
		Handler: hostPortStrip(mux),
	}
	err = server.Serve(hl)
	logger.Shout("Server stopped: %v", err)
	return nil
}