Cgi and file server

This is an example Go program which illustrates making a CGI and file server.

package main

import (
        "log"
        "net/http"
        "net/http/cgi"
        "strings"
)

var fileserver http.Handler

// The root directory for the web server.

var dir string = "/usr/local/www/data"

func cgifile(w http.ResponseWriter, r *http.Request) {
        if strings.Contains(r.RequestURI, ".cgi") {
                path := dir + r.RequestURI
                qmark := strings.Index(path, "?")
                if qmark > 0 {
                        path = path[0:qmark]
                }
                h := &cgi.Handler{
                        Path: path,
                }
                h.ServeHTTP(w, r)
        } else {
                fileserver.ServeHTTP(w, r)
        }
}

func main() {
        fileserver = http.FileServer(http.Dir(dir))
        http.HandleFunc("/", cgifile)
        err := http.ListenAndServe(":8080", nil)
        if err != nil {
                log.Fatal(err)
        }
}

(download)


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer