From 1e0f8e0aaeaf1bd2ee39c02e922238b641bcf88b Mon Sep 17 00:00:00 2001 From: tjp Date: Mon, 13 Nov 2023 07:25:39 -0700 Subject: refactor contribs to work with a Protocol interface --- contrib/cgi/handlers.go | 57 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 contrib/cgi/handlers.go (limited to 'contrib/cgi/handlers.go') 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 + }) +} -- cgit v1.2.3