summaryrefslogtreecommitdiff
path: root/nex.go
blob: bd9bdce0bc9df48c729ff909c87fb77382dfe552 (plain)
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
74
75
76
77
78
79
package main

import (
	"context"
	"fmt"

	"github.com/go-kit/log/level"

	sr "tildegit.org/tjp/sliderule"
	"tildegit.org/tjp/sliderule/contrib/cgi"
	"tildegit.org/tjp/sliderule/contrib/fs"
	"tildegit.org/tjp/sliderule/logging"
	"tildegit.org/tjp/sliderule/nex"
)

func buildNexServer(server Server, config *Configuration) (sr.Server, error) {
	addr := fmt.Sprintf("%s:%d", server.IP.String(), server.Port)

	baselog := BaseLogger(config)
	info := level.Info(baselog)
	errlog := level.Error(baselog)

	if server.TLS != nil {
		return nex.NewTLSServer(
			context.Background(),
			server.Hostnames[0],
			"tcp",
			addr,
			logging.LogRequests(info)(routes(server)),
			errlog,
			server.TLS,
		)
	} else {
		return nex.NewServer(
			context.Background(),
			server.Hostnames[0],
			"tcp",
			addr,
			logging.LogRequests(info)(routes(server)),
			errlog,
		)
	}
}

func addNexRoute(router *sr.Router, route RouteDirective) {
	switch route.Type {
	case "static":
		addNexStaticRoute(router, route)
	case "cgi":
		buildAndAddRoute(router, route, func(route RouteDirective) sr.Handler {
			return cgi.NexCGIDirectory(route.FsPath, route.URLPath, route.Modifiers.ExecCmd)
		})
	}
}

func addNexStaticRoute(router *sr.Router, route RouteDirective) {
	buildAndAddRoute(router, route, func(route RouteDirective) sr.Handler {
		handlers := []sr.Handler{}

		if route.Modifiers.Exec {
			handlers = append(handlers, cgi.NexCGIDirectory(route.FsPath, route.URLPath, route.Modifiers.ExecCmd))
		}

		handlers = append(handlers, fs.NexFileHandler(route.FsPath, route.URLPath))

		if route.Modifiers.DirDefault != "" {
			handlers = append(
				handlers,
				fs.NexDirectoryDefault(route.FsPath, route.URLPath, route.Modifiers.DirDefault),
			)
		}

		if route.Modifiers.DirList {
			handlers = append(handlers, fs.NexDirectoryListing(route.FsPath, route.URLPath, nil))
		}

		return sr.FallthroughHandler(handlers...)
	})
}