Example #1
0
func TestSetup(t *testing.T) {
	c := caddy.NewTestController("http", `expvar`)
	err := setup(c)
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}
	mids := httpserver.GetConfig(c).Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, got 0 instead")
	}

	c = caddy.NewTestController("http", `expvar /d/v`)
	err = setup(c)
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}
	mids = httpserver.GetConfig(c).Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, got 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(ExpVar)
	if !ok {
		t.Fatalf("Expected handler to be type ExpVar, got: %#v", handler)
	}
	if myHandler.Resource != "/d/v" {
		t.Errorf("Expected /d/v as expvar resource")
	}
	if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
		t.Error("'Next' field of handler was not set properly")
	}
}
Example #2
0
func TestSetup(t *testing.T) {
	c := caddy.NewTestController("http", `internal /internal`)
	err := setup(c)
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}
	mids := httpserver.GetConfig(c).Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, got 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(Internal)

	if !ok {
		t.Fatalf("Expected handler to be type Internal, got: %#v", handler)
	}

	if myHandler.Paths[0] != "/internal" {
		t.Errorf("Expected internal in the list of internal Paths")
	}

	if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
		t.Error("'Next' field of handler was not set properly")
	}

}
Example #3
0
func TestSetup(t *testing.T) {
	c := caddy.NewTestController("http", `ext .html .htm .php`)
	err := setup(c)
	if err != nil {
		t.Fatalf("Expected no errors, got: %v", err)
	}

	mids := httpserver.GetConfig(c).Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, had 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(Ext)

	if !ok {
		t.Fatalf("Expected handler to be type Ext, got: %#v", handler)
	}

	if myHandler.Extensions[0] != ".html" {
		t.Errorf("Expected .html in the list of Extensions")
	}
	if myHandler.Extensions[1] != ".htm" {
		t.Errorf("Expected .htm in the list of Extensions")
	}
	if myHandler.Extensions[2] != ".php" {
		t.Errorf("Expected .php in the list of Extensions")
	}
	if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
		t.Error("'Next' field of handler was not set properly")
	}

}
Example #4
0
func TestSetup(t *testing.T) {
	c := caddy.NewTestController("http", `rewrite /from /to`)
	err := setup(c)
	if err != nil {
		t.Errorf("Expected no errors, but got: %v", err)
	}
	mids := httpserver.GetConfig(c).Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, had 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(Rewrite)
	if !ok {
		t.Fatalf("Expected handler to be type Rewrite, got: %#v", handler)
	}

	if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
		t.Error("'Next' field of handler was not set properly")
	}

	if len(myHandler.Rules) != 1 {
		t.Errorf("Expected handler to have %d rule, has %d instead", 1, len(myHandler.Rules))
	}
}
Example #5
0
func TestWebSocket(t *testing.T) {
	err := setup(caddy.NewTestController(`websocket cat`))
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}
	mids := httpserver.GetConfig("").Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, got 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(WebSocket)

	if !ok {
		t.Fatalf("Expected handler to be type WebSocket, got: %#v", handler)
	}

	if myHandler.Sockets[0].Path != "/" {
		t.Errorf("Expected / as the default Path")
	}
	if myHandler.Sockets[0].Command != "cat" {
		t.Errorf("Expected %s as the command", "cat")
	}

}
Example #6
0
func TestSetup(t *testing.T) {

	for j, test := range []struct {
		input         string
		shouldErr     bool
		expectedRules []Rule
	}{
		// test case #0 tests the recognition of a valid HTTP status code defined outside of block statement
		{"redir 300 {\n/ /foo\n}", false, []Rule{{FromPath: "/", To: "/foo", Code: 300}}},

		// test case #1 tests the recognition of an invalid HTTP status code defined outside of block statement
		{"redir 9000 {\n/ /foo\n}", true, []Rule{{}}},

		// test case #2 tests the detection of a valid HTTP status code outside of a block statement being overriden by an invalid HTTP status code inside statement of a block statement
		{"redir 300 {\n/ /foo 9000\n}", true, []Rule{{}}},

		// test case #3 tests the detection of an invalid HTTP status code outside of a block statement being overriden by a valid HTTP status code inside statement of a block statement
		{"redir 9000 {\n/ /foo 300\n}", true, []Rule{{}}},

		// test case #4 tests the recognition of a TO redirection in a block statement.The HTTP status code is set to the default of 301 - MovedPermanently
		{"redir 302 {\n/foo\n}", false, []Rule{{FromPath: "/", To: "/foo", Code: 302}}},

		// test case #5 tests the recognition of a TO and From redirection in a block statement
		{"redir {\n/bar /foo 303\n}", false, []Rule{{FromPath: "/bar", To: "/foo", Code: 303}}},

		// test case #6 tests the recognition of a TO redirection in a non-block statement. The HTTP status code is set to the default of 301 - MovedPermanently
		{"redir /foo", false, []Rule{{FromPath: "/", To: "/foo", Code: 301}}},

		// test case #7 tests the recognition of a TO and From redirection in a non-block statement
		{"redir /bar /foo 303", false, []Rule{{FromPath: "/bar", To: "/foo", Code: 303}}},

		// test case #8 tests the recognition of multiple redirections
		{"redir {\n / /foo 304 \n} \n redir {\n /bar /foobar 305 \n}", false, []Rule{{FromPath: "/", To: "/foo", Code: 304}, {FromPath: "/bar", To: "/foobar", Code: 305}}},

		// test case #9 tests the detection of duplicate redirections
		{"redir {\n /bar /foo 304 \n} redir {\n /bar /foo 304 \n}", true, []Rule{{}}},
	} {
		err := setup(caddy.NewTestController(test.input))
		if err != nil && !test.shouldErr {
			t.Errorf("Test case #%d recieved an error of %v", j, err)
		} else if test.shouldErr {
			continue
		}
		mids := httpserver.GetConfig("").Middleware()
		recievedRules := mids[len(mids)-1](nil).(Redirect).Rules

		for i, recievedRule := range recievedRules {
			if recievedRule.FromPath != test.expectedRules[i].FromPath {
				t.Errorf("Test case #%d.%d expected a from path of %s, but recieved a from path of %s", j, i, test.expectedRules[i].FromPath, recievedRule.FromPath)
			}
			if recievedRule.To != test.expectedRules[i].To {
				t.Errorf("Test case #%d.%d expected a TO path of %s, but recieved a TO path of %s", j, i, test.expectedRules[i].To, recievedRule.To)
			}
			if recievedRule.Code != test.expectedRules[i].Code {
				t.Errorf("Test case #%d.%d expected a HTTP status code of %d, but recieved a code of %d", j, i, test.expectedRules[i].Code, recievedRule.Code)
			}
		}
	}

}
Example #7
0
// setup configures a new FastCGI middleware instance.
func setup(c *caddy.Controller) error {
	cfg := httpserver.GetConfig(c.Key)
	absRoot, err := filepath.Abs(cfg.Root)
	if err != nil {
		return err
	}

	rules, err := fastcgiParse(c)
	if err != nil {
		return err
	}

	cfg.AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
		return Handler{
			Next:            next,
			Rules:           rules,
			Root:            cfg.Root,
			AbsRoot:         absRoot,
			FileSys:         http.Dir(cfg.Root),
			SoftwareName:    caddy.AppName,
			SoftwareVersion: caddy.AppVersion,
			ServerName:      cfg.Addr.Host,
			ServerPort:      cfg.Addr.Port,
		}
	})

	return nil
}
Example #8
0
func TestSetup(t *testing.T) {
	err := setup(caddy.NewTestController(`errors`))
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}
	mids := httpserver.GetConfig("").Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middlewares, was nil instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(*ErrorHandler)
	if !ok {
		t.Fatalf("Expected handler to be type ErrorHandler, got: %#v", handler)
	}

	if myHandler.LogFile != "" {
		t.Errorf("Expected '%s' as the default LogFile", "")
	}
	if myHandler.LogRoller != nil {
		t.Errorf("Expected LogRoller to be nil, got: %v", *myHandler.LogRoller)
	}
	if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
		t.Error("'Next' field of handler was not set properly")
	}

	// Test Startup function -- TODO
	// if len(c.Startup) == 0 {
	// 	t.Fatal("Expected 1 startup function, had 0")
	// }
	// c.Startup[0]()
	// if myHandler.Log == nil {
	// 	t.Error("Expected Log to be non-nil after startup because Debug is not enabled")
	// }
}
Example #9
0
func TestSetup(t *testing.T) {
	err := setup(caddy.NewTestController(`templates`))
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}
	mids := httpserver.GetConfig("").Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, got 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(Templates)

	if !ok {
		t.Fatalf("Expected handler to be type Templates, got: %#v", handler)
	}

	if myHandler.Rules[0].Path != defaultTemplatePath {
		t.Errorf("Expected / as the default Path")
	}
	if fmt.Sprint(myHandler.Rules[0].Extensions) != fmt.Sprint(defaultTemplateExtensions) {
		t.Errorf("Expected %v to be the Default Extensions", defaultTemplateExtensions)
	}
	var indexFiles []string
	for _, extension := range defaultTemplateExtensions {
		indexFiles = append(indexFiles, "index"+extension)
	}
	if fmt.Sprint(myHandler.Rules[0].IndexFiles) != fmt.Sprint(indexFiles) {
		t.Errorf("Expected %v to be the Default Index files", indexFiles)
	}
	if myHandler.Rules[0].Delims != [2]string{} {
		t.Errorf("Expected %v to be the Default Delims", [2]string{})
	}
}
Example #10
0
func TestSetup(t *testing.T) {
	c := caddy.NewTestController("http", `markdown /blog`)
	err := setup(c)
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}
	mids := httpserver.GetConfig(c).Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, got 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(Markdown)

	if !ok {
		t.Fatalf("Expected handler to be type Markdown, got: %#v", handler)
	}

	if myHandler.Configs[0].PathScope != "/blog" {
		t.Errorf("Expected /blog as the Path Scope")
	}
	if len(myHandler.Configs[0].Extensions) != 3 {
		t.Error("Expected 3 markdown extensions")
	}
	for _, key := range []string{".md", ".markdown", ".mdown"} {
		if ext, ok := myHandler.Configs[0].Extensions[key]; !ok {
			t.Errorf("Expected extensions to contain %v", ext)
		}
	}
}
Example #11
0
// Setup is the init function of Caddy plugins and it configures the whole
// middleware thing.
func setup(c *caddy.Controller) error {
	cnf := httpserver.GetConfig(c)

	conf, fm, err := parse(c, cnf.Root)

	if err != nil {
		return err
	}

	// Generates the Hugo website for the first time the plugin is activated.
	go RunHugo(conf, true)

	mid := func(next httpserver.Handler) httpserver.Handler {
		fm.Next = next

		return &Hugo{
			Next:        next,
			Config:      conf,
			FileManager: fm,
		}
	}

	cnf.AddMiddleware(mid)
	return nil
}
Example #12
0
func TestSetup(t *testing.T) {
	c := caddy.NewTestController("http", `fastcgi / 127.0.0.1:9000`)
	err := setup(c)
	if err != nil {
		t.Errorf("Expected no errors, got: %v", err)
	}
	mids := httpserver.GetConfig(c).Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, got 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(Handler)

	if !ok {
		t.Fatalf("Expected handler to be type , got: %#v", handler)
	}

	if myHandler.Rules[0].Path != "/" {
		t.Errorf("Expected / as the Path")
	}
	if myHandler.Rules[0].Address != "127.0.0.1:9000" {
		t.Errorf("Expected 127.0.0.1:9000 as the Address")
	}

}
Example #13
0
// setup configures a new Git service routine.
func setup(c *caddy.Controller) error {
	git, err := parse(c)
	if err != nil {
		return err
	}

	// repos configured with webhooks
	var hookRepos []*Repo

	// functions to execute at startup
	var startupFuncs []func() error

	// loop through all repos and and start monitoring
	for i := range git {
		repo := git.Repo(i)

		// If a HookUrl is set, we switch to event based pulling.
		// Install the url handler
		if repo.Hook.URL != "" {

			hookRepos = append(hookRepos, repo)

			startupFuncs = append(startupFuncs, func() error {
				return repo.Pull()
			})

		} else {
			startupFuncs = append(startupFuncs, func() error {

				// Start service routine in background
				Start(repo)

				// Do a pull right away to return error
				return repo.Pull()
			})
		}
	}

	// ensure the functions are executed once per server block
	// for cases like server1.com, server2.com { ... }
	c.OncePerServerBlock(func() error {
		for i := range startupFuncs {
			c.OnStartup(startupFuncs[i])
		}
		return nil
	})

	// if there are repo(s) with webhook
	// return handler
	if len(hookRepos) > 0 {
		webhook := &WebHook{Repos: hookRepos}
		httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
			webhook.Next = next
			return webhook
		})
	}

	return nil
}
Example #14
0
// setup sets up the logging middleware.
func setup(c *caddy.Controller) error {
	rules, err := logParse(c)
	if err != nil {
		return err
	}

	// Open the log files for writing when the server starts
	c.OnStartup(func() error {
		for i := 0; i < len(rules); i++ {
			var err error
			var writer io.Writer

			if rules[i].OutputFile == "stdout" {
				writer = os.Stdout
			} else if rules[i].OutputFile == "stderr" {
				writer = os.Stderr
			} else if rules[i].OutputFile == "syslog" {
				writer, err = gsyslog.NewLogger(gsyslog.LOG_INFO, "LOCAL0", "caddy")
				if err != nil {
					return err
				}
			} else {
				var file *os.File
				file, err = os.OpenFile(rules[i].OutputFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
				if err != nil {
					return err
				}
				if rules[i].Roller != nil {
					file.Close()
					rules[i].Roller.Filename = rules[i].OutputFile
					writer = rules[i].Roller.GetLogWriter()
				} else {
					rules[i].file = file
					writer = file
				}
			}

			rules[i].Log = log.New(writer, "", 0)
		}

		return nil
	})

	// When server stops, close any open log files
	c.OnShutdown(func() error {
		for _, rule := range rules {
			if rule.file != nil {
				rule.file.Close()
			}
		}
		return nil
	})

	httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
		return Logger{Next: next, Rules: rules, ErrorFunc: httpserver.DefaultErrorFunc}
	})

	return nil
}
Example #15
0
func loadParams(c *caddy.Controller, mdc *Config) error {
	cfg := httpserver.GetConfig(c.Key)

	switch c.Val() {
	case "ext":
		for _, ext := range c.RemainingArgs() {
			mdc.Extensions[ext] = struct{}{}
		}
		return nil
	case "css":
		if !c.NextArg() {
			return c.ArgErr()
		}
		mdc.Styles = append(mdc.Styles, c.Val())
		return nil
	case "js":
		if !c.NextArg() {
			return c.ArgErr()
		}
		mdc.Scripts = append(mdc.Scripts, c.Val())
		return nil
	case "template":
		tArgs := c.RemainingArgs()
		switch len(tArgs) {
		default:
			return c.ArgErr()
		case 1:
			fpath := filepath.ToSlash(filepath.Clean(cfg.Root + string(filepath.Separator) + tArgs[0]))

			if err := SetTemplate(mdc.Template, "", fpath); err != nil {
				c.Errf("default template parse error: %v", err)
			}
			return nil
		case 2:
			fpath := filepath.ToSlash(filepath.Clean(cfg.Root + string(filepath.Separator) + tArgs[1]))

			if err := SetTemplate(mdc.Template, tArgs[0], fpath); err != nil {
				c.Errf("template parse error: %v", err)
			}
			return nil
		}
	case "templatedir":
		if !c.NextArg() {
			return c.ArgErr()
		}
		_, err := mdc.Template.ParseGlob(c.Val())
		if err != nil {
			c.Errf("template load error: %v", err)
		}
		if c.NextArg() {
			return c.ArgErr()
		}
		return nil
	default:
		return c.Err("Expected valid markdown configuration property")
	}
}
Example #16
0
// setup configures a new errors middleware instance.
func setup(c *caddy.Controller) error {
	handler, err := errorsParse(c)
	if err != nil {
		return err
	}

	// Open the log file for writing when the server starts
	c.OnStartup(func() error {
		var err error
		var writer io.Writer

		switch handler.LogFile {
		case "visible":
			handler.Debug = true
		case "stdout":
			writer = os.Stdout
		case "stderr":
			writer = os.Stderr
		case "syslog":
			writer, err = gsyslog.NewLogger(gsyslog.LOG_ERR, "LOCAL0", "caddy")
			if err != nil {
				return err
			}
		default:
			if handler.LogFile == "" {
				writer = os.Stderr // default
				break
			}

			var file *os.File
			file, err = os.OpenFile(handler.LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
			if err != nil {
				return err
			}
			if handler.LogRoller != nil {
				file.Close()

				handler.LogRoller.Filename = handler.LogFile

				writer = handler.LogRoller.GetLogWriter()
			} else {
				writer = file
			}
		}

		handler.Log = log.New(writer, "", 0)
		return nil
	})

	httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
		handler.Next = next
		return handler
	})

	return nil
}
Example #17
0
func setupBind(c *caddy.Controller) error {
	config := httpserver.GetConfig(c)
	for c.Next() {
		if !c.Args(&config.ListenHost) {
			return c.ArgErr()
		}
		config.TLS.ListenHost = config.ListenHost // necessary for ACME challenges, see issue #309
	}
	return nil
}
Example #18
0
// setup configures a new Proxy middleware instance.
func setup(c *caddy.Controller) error {
	upstreams, err := NewStaticUpstreams(c.Dispenser)
	if err != nil {
		return err
	}
	httpserver.GetConfig(c.Key).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
		return Proxy{Next: next, Upstreams: upstreams}
	})
	return nil
}
Example #19
0
// setup configures a new instance of 'extensions' middleware for clean URLs.
func setup(c *caddy.Controller) error {
	cfg := httpserver.GetConfig(c.Key)
	root := cfg.Root

	exts, err := extParse(c)
	if err != nil {
		return err
	}

	httpserver.GetConfig(c.Key).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
		return Ext{
			Next:       next,
			Extensions: exts,
			Root:       root,
		}
	})

	return nil
}
Example #20
0
func TestSetup(t *testing.T) {
	tempDirPath := os.TempDir()
	_, err := os.Stat(tempDirPath)
	if err != nil {
		t.Fatalf("BeforeTest: Failed to find an existing directory for testing! Error was: %v", err)
	}
	nonExistantDirPath := filepath.Join(tempDirPath, strconv.Itoa(int(time.Now().UnixNano())))

	tempTemplate, err := ioutil.TempFile(".", "tempTemplate")
	if err != nil {
		t.Fatalf("BeforeTest: Failed to create a temporary file in the working directory! Error was: %v", err)
	}
	defer os.Remove(tempTemplate.Name())

	tempTemplatePath := filepath.Join(".", tempTemplate.Name())

	for i, test := range []struct {
		input             string
		expectedPathScope []string
		shouldErr         bool
	}{
		// test case #0 tests handling of multiple pathscopes
		{"browse " + tempDirPath + "\n browse .", []string{tempDirPath, "."}, false},

		// test case #1 tests instantiation of Config with default values
		{"browse /", []string{"/"}, false},

		// test case #2 tests detectaction of custom template
		{"browse . " + tempTemplatePath, []string{"."}, false},

		// test case #3 tests detection of non-existent template
		{"browse . " + nonExistantDirPath, nil, true},

		// test case #4 tests detection of duplicate pathscopes
		{"browse " + tempDirPath + "\n browse " + tempDirPath, nil, true},
	} {

		c := caddy.NewTestController("http", test.input)
		err := setup(c)
		if err != nil && !test.shouldErr {
			t.Errorf("Test case #%d recieved an error of %v", i, err)
		}
		if test.expectedPathScope == nil {
			continue
		}
		mids := httpserver.GetConfig(c).Middleware()
		mid := mids[len(mids)-1]
		recievedConfigs := mid(nil).(Browse).Configs
		for j, config := range recievedConfigs {
			if config.PathScope != test.expectedPathScope[j] {
				t.Errorf("Test case #%d expected a pathscope of %v, but got %v", i, test.expectedPathScope, config.PathScope)
			}
		}
	}
}
Example #21
0
func browseParse(c *caddy.Controller) ([]Config, error) {
	var configs []Config

	cfg := httpserver.GetConfig(c)

	appendCfg := func(bc Config) error {
		for _, c := range configs {
			if c.PathScope == bc.PathScope {
				return fmt.Errorf("duplicate browsing config for %s", c.PathScope)
			}
		}
		configs = append(configs, bc)
		return nil
	}

	for c.Next() {
		var bc Config

		// First argument is directory to allow browsing; default is site root
		if c.NextArg() {
			bc.PathScope = c.Val()
		} else {
			bc.PathScope = "/"
		}
		bc.Root = http.Dir(cfg.Root)

		// Second argument would be the template file to use
		var tplText string
		if c.NextArg() {
			tplBytes, err := ioutil.ReadFile(c.Val())
			if err != nil {
				return configs, err
			}
			tplText = string(tplBytes)
		} else {
			tplText = defaultTemplate
		}

		// Build the template
		tpl, err := template.New("listing").Parse(tplText)
		if err != nil {
			return configs, err
		}
		bc.Template = tpl

		// Save configuration
		err = appendCfg(bc)
		if err != nil {
			return configs, err
		}
	}

	return configs, nil
}
Example #22
0
func TestSetup(t *testing.T) {
	c := caddy.NewTestController("http", `mime .txt text/plain`)
	err := setup(c)
	if err != nil {
		t.Errorf("Expected no errors, but got: %v", err)
	}
	mids := httpserver.GetConfig(c).Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, but had 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(Mime)
	if !ok {
		t.Fatalf("Expected handler to be type Mime, got: %#v", handler)
	}

	if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
		t.Error("'Next' field of handler was not set properly")
	}

	tests := []struct {
		input     string
		shouldErr bool
	}{
		{`mime {`, true},
		{`mime {}`, true},
		{`mime a b`, true},
		{`mime a {`, true},
		{`mime { txt f } `, true},
		{`mime { html } `, true},
		{`mime {
		 .html text/html
		 .txt text/plain
		} `, false},
		{`mime {
		 .foo text/foo
		 .bar text/bar
		 .foo text/foobar
		} `, true},
		{`mime { .html text/html } `, false},
		{`mime { .html
		} `, true},
		{`mime .txt text/plain`, false},
	}
	for i, test := range tests {
		m, err := mimeParse(caddy.NewTestController("http", test.input))
		if test.shouldErr && err == nil {
			t.Errorf("Test %v: Expected error but found nil %v", i, m)
		} else if !test.shouldErr && err != nil {
			t.Errorf("Test %v: Expected no error but found error: %v", i, err)
		}
	}
}
Example #23
0
func setup(c *caddy.Controller) error {
	config, err := nlgidsParse(c)
	if err != nil {
		return err
	}
	httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
		return &NLgids{Next: next, Config: config}
	})

	return nil
}
Example #24
0
// setup configures a new Redirect middleware instance.
func setup(c *caddy.Controller) error {
	rules, err := redirParse(c)
	if err != nil {
		return err
	}

	httpserver.GetConfig(c.Key).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
		return Redirect{Next: next, Rules: rules}
	})

	return nil
}
Example #25
0
// setup configures a new Headers middleware instance.
func setup(c *caddy.Controller) error {
	rules, err := headersParse(c)
	if err != nil {
		return err
	}

	httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
		return Headers{Next: next, Rules: rules}
	})

	return nil
}
Example #26
0
// setup configures a new gzip middleware instance.
func setup(c *caddy.Controller) error {
	configs, err := gzipParse(c)
	if err != nil {
		return err
	}

	httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
		return Gzip{Next: next, Configs: configs}
	})

	return nil
}
Example #27
0
// Internal configures a new Internal middleware instance.
func setup(c *caddy.Controller) error {
	paths, err := internalParse(c)
	if err != nil {
		return err
	}

	httpserver.GetConfig(c.Key).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
		return Internal{Next: next, Paths: paths}
	})

	return nil
}
Example #28
0
// Setup creates a new middleware with the given configuration
func Setup(c *caddy.Controller) (err error) {
	cfg := httpserver.GetConfig(c)
	var config *Config

	config, err = ParseSearchConfig(c, cfg)
	if err != nil {
		return err
	}

	index, err := NewIndexer(config.Engine, indexer.Config{
		HostName:       config.HostName,
		IndexDirectory: config.IndexDirectory,
	})

	if err != nil {
		return err
	}

	ppl, err := NewPipeline(config, index)

	if err != nil {
		return err
	}

	expire := time.NewTicker(config.Expire)
	go func() {
		var lastScanned indexer.Record
		lastScanned = ScanToPipe(config.SiteRoot, ppl, index)

		for {
			select {
			case <-expire.C:
				if lastScanned != nil && (!lastScanned.Indexed().IsZero() || lastScanned.Ignored()) {
					lastScanned = ScanToPipe(config.SiteRoot, ppl, index)
				}
			}
		}
	}()

	search := &Search{
		Config:   config,
		Indexer:  index,
		Pipeline: ppl,
	}

	cfg.AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
		search.Next = next
		return search
	})

	return
}
Example #29
0
func setupMaxRequestBody(c *caddy.Controller) error {
	config := httpserver.GetConfig(c)

	if !c.Next() {
		return c.ArgErr()
	}

	args := c.RemainingArgs()
	argList := []pathLimitUnparsed{}

	switch len(args) {
	case 0:
		// Format: { <path> <limit> ... }
		for c.NextBlock() {
			path := c.Val()
			if !c.NextArg() {
				// Uneven pairing of path/limit
				return c.ArgErr()
			}
			argList = append(argList, pathLimitUnparsed{
				Path:  path,
				Limit: c.Val(),
			})
		}
	case 1:
		// Format: <limit>
		argList = []pathLimitUnparsed{{
			Path:  "/",
			Limit: args[0],
		}}
	case 2:
		// Format: <path> <limit>
		argList = []pathLimitUnparsed{{
			Path:  args[0],
			Limit: args[1],
		}}
	default:
		return c.ArgErr()
	}

	pathLimit, err := parseArguments(argList)
	if err != nil {
		return c.ArgErr()
	}

	SortPathLimits(pathLimit)

	config.MaxRequestBodySizes = pathLimit

	return nil
}
Example #30
0
func TestSetupBind(t *testing.T) {
	err := setupBind(caddy.NewTestController(`bind 1.2.3.4`))
	if err != nil {
		t.Fatalf("Expected no errors, but got: %v", err)
	}

	cfg := httpserver.GetConfig("")
	if got, want := cfg.ListenHost, "1.2.3.4"; got != want {
		t.Errorf("Expected the config's ListenHost to be %s, was %s", want, got)
	}
	if got, want := cfg.TLS.ListenHost, "1.2.3.4"; got != want {
		t.Errorf("Expected the TLS config's ListenHost to be %s, was %s", want, got)
	}
}