Gitart
10/29/2016 - 3:33 PM

Simple service

Simple service

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/julienschmidt/httprouter"
)

// *****************************************************************************
// Application Logic
// *****************************************************************************

var (
	allowDirBrowsing = true
	publicFolder     = "public"
)

func init() {
	// Verbose logging with file name and line number
	log.SetFlags(log.Lshortfile)
}

// HandlerFunc accepts the name of a function so you don't have to wrap it with http.HandlerFunc
// Example: r.GET("/", httprouterwrapper.HandlerFunc(controller.Index))
func HandlerFunc(h http.HandlerFunc) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
		fmt.Println(time.Now().Format("2006-01-02 03:04:05 PM"), r.RemoteAddr, r.Method, r.URL)
		h.ServeHTTP(w, r)
	}
}

// Error404 handles 404 - Page Not Found
func Error404(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusNotFound)
	fmt.Fprint(w, "Not Found 404")
}

// Static maps static files
func Static(w http.ResponseWriter, r *http.Request) {
	// If directory browing is enabled
	if !allowDirBrowsing {
		// Disable listing directories
		if strings.HasSuffix(r.URL.Path, "/") {
			Error404(w, r)
			return
		}
	}

	// Get the file name
	filename := publicFolder + "/" + r.URL.Path[1:]

	// If the file exists
	if _, err := os.Stat(filename); err == nil {
		http.ServeFile(w, r, filename)
	} else {
		Error404(w, r)
	}
}

func main() {
	r := httprouter.New()

	// Set 404 handler
	r.NotFound = http.HandlerFunc(Error404)

	// Serve static files, no directory browsing
	r.GET("/*filepath", HandlerFunc(Static))
	r.HEAD("/*filepath", HandlerFunc(Static))
	r.POST("/*filepath", HandlerFunc(Static))
	r.DELETE("/*filepath", HandlerFunc(Static))
	r.PATCH("/*filepath", HandlerFunc(Static))
	r.PUT("/*filepath", HandlerFunc(Static))
	r.OPTIONS("/*filepath", HandlerFunc(Static))

	// Output the server information
	fmt.Println(time.Now().Format("2006-01-02 03:04:05 PM"), "Running HTTP on :80")

	// Start the HTTP listener
	log.Fatal(http.ListenAndServe(":80", r))
}