Last active
September 18, 2015 22:15
-
-
Save josephspurrier/98623f26d64b54ef5663 to your computer and use it in GitHub Desktop.
Simple Webserver in Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment