package main import ( "io" "net/http" "os" "time" ) // UnauthorizedIfNotLocal is a middleware that returns unauthorized if not // being accessed from loopback, as a basic form of host authentication. func UnauthorizedIfNotLocal(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !isLocal(r.RemoteAddr) { http.Error(w, "Unauthorized", http.StatusUnauthorized) Logger.Printf("Unauthorized request from: %s for %s", r.RemoteAddr, r.RequestURI) return } h.ServeHTTP(w, r) }) } // HandleSelfServe tries to locate the currently running executable and serve // it down to the client. func HandleSelfServe() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { s, err := os.Executable() if err != nil { Logger.Println("While trying to get my executable path: ", err) http.Error(w, "Internal server error", http.StatusInternalServerError) return } fh, err := os.Open(s) if err != nil { Logger.Println("While opening my own executable for reading: ", err) http.Error(w, "Internal server error", http.StatusInternalServerError) return } _, err = io.Copy(w, fh) fh.Close() return }) } // HandleQuit just calls os.Exit after finishing the request func HandleQuit(w http.ResponseWriter, r *http.Request) { Logger.Println("Quit was called, exiting") w.Header().Add("Content-type", "text/plain") w.Write([]byte("Shutting down... feel free to close this")) go func() { time.Sleep(time.Millisecond * 50) os.Exit(0) }() return }