summaryrefslogtreecommitdiff
path: root/contrib/cgi/spartan.go
blob: 01ebb1912bdad61ed2f024f7d84ad4cc5d386c82 (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
package cgi

import (
	"context"
	"fmt"
	"strings"

	"tildegit.org/tjp/gus"
	"tildegit.org/tjp/gus/spartan"
)

// SpartanCGIDirectory runs executable files relative to a root directory in the file system.
//
// It will also find any run any executable _part way_ through the path, so for example a
// request for /foo/bar/baz can also run an executable found at /foo or /foo/bar. In such
// a case the PATH_INFO environment variable will include the remaining portion of the URI.
func SpartanCGIDirectory(pathRoot, fsRoot string) gus.Handler {
	fsRoot = strings.TrimRight(fsRoot, "/")
	return gus.HandlerFunc(func(ctx context.Context, request *gus.Request) *gus.Response {
		if !strings.HasPrefix(request.Path, pathRoot) {
			return nil
		}

		filepath, pathinfo, err := ResolveCGI(request.Path[len(pathRoot):], fsRoot)
		if err != nil {
			return spartan.ServerError(err)
		}
		if filepath == "" {
			return nil
		}

		stdout, exitCode, err := RunCGI(ctx, request, filepath, pathinfo)
		if err != nil {
			return spartan.ServerError(err)
		}
		if exitCode != 0 {
			return spartan.ServerError(fmt.Errorf("CGI process exited with status %d", exitCode))
		}

		response, err := spartan.ParseResponse(stdout)
		if err != nil {
			return spartan.ServerError(err)
		}
		return response
	})
}