diff options
author | tjp <tjp@ctrl-c.club> | 2023-11-13 07:25:39 -0700 |
---|---|---|
committer | tjp <tjp@ctrl-c.club> | 2023-11-13 07:27:16 -0700 |
commit | 1e0f8e0aaeaf1bd2ee39c02e922238b641bcf88b (patch) | |
tree | 020e5de91f2343119fed10dede9d2c8262a3cd83 /contrib/cgi/handlers.go | |
parent | a808b4692656c10bb43e2d54a2f5ef2746d231d5 (diff) |
refactor contribs to work with a Protocol interface
Diffstat (limited to 'contrib/cgi/handlers.go')
-rw-r--r-- | contrib/cgi/handlers.go | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/contrib/cgi/handlers.go b/contrib/cgi/handlers.go new file mode 100644 index 0000000..03a1db7 --- /dev/null +++ b/contrib/cgi/handlers.go @@ -0,0 +1,57 @@ +package cgi + +import ( + "bytes" + "context" + "fmt" + "path/filepath" + "strings" + + sr "tildegit.org/tjp/sliderule" + "tildegit.org/tjp/sliderule/logging" +) + +func cgiDirectory(protocol sr.ServerProtocol, fsroot, urlroot, cmd string) sr.Handler { + fsroot = strings.TrimRight(fsroot, "/") + + return sr.HandlerFunc(func(ctx context.Context, request *sr.Request) *sr.Response { + if !strings.HasPrefix(request.Path, urlroot) { + return nil + } + + rpath := strings.TrimPrefix(request.Path, urlroot) + rpath = strings.Trim(rpath, "/") + execpath, pathinfo, err := ResolveCGI(rpath, fsroot) + if err != nil { + return protocol.TemporaryServerError(err) + } + if execpath == "" { + return nil + } + workdir := filepath.Dir(execpath) + + if cmd != "" { + execpath = cmd + } + + stderr := &bytes.Buffer{} + stdout, exitCode, err := RunCGI(ctx, request, execpath, pathinfo, workdir, stderr) + if err != nil { + return protocol.TemporaryServerError(err) + } + if exitCode != 0 { + _ = ctx.Value("warnlog").(logging.Logger).Log( + "msg", "cgi exited with non-zero exit code", + "code", exitCode, + "stderr", stderr.String(), + ) + return protocol.CGIFailure(fmt.Errorf("CGI process exited with status %d", exitCode)) + } + + response, err := protocol.ParseResponse(stdout) + if err != nil { + return protocol.TemporaryServerError(err) + } + return response + }) +} |