// Servecgi serves HTTP requests on the specified network address, invoking a
// CGI program for each request.
// Usage: servecgi [-l addr] cgi-prog
package main

import (
	"flag"
	"log"
	"net/http"
	"net/http/cgi"
	"os"
)

var addr = flag.String("l", getEnvDefault("SERVECGI_LADDR", ":80"),
	"local network `addr` to listen on")

func main() {
	if flag.Parse(); flag.NArg() != 1 {
		log.Fatalf("usage: %s [-l addr] path-to-cgi-executable", os.Args[0])
	}

	http.Handle("/", &cgi.Handler{Path: flag.Arg(0)})
	log.Fatal(http.ListenAndServe(*addr, nil))
}

// GetEnvOrDefault retrieves the value associated with key from the environment
// block. If the value is the empty string, or not present at all, defValue is
// returned.
func getEnvDefault(key, defValue string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return defValue
}