From 0fc3eda77004f41c5f0a804028da2d90b0373ea7 Mon Sep 17 00:00:00 2001 From: Mitchell Riedstra Date: Tue, 24 Aug 2021 22:25:40 -0400 Subject: Another development snapshot. Updated license. Added Swagger documentation--embedded! Note about 'swaggo' --- cmd/web/handlers_util.go | 58 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 cmd/web/handlers_util.go (limited to 'cmd/web/handlers_util.go') diff --git a/cmd/web/handlers_util.go b/cmd/web/handlers_util.go new file mode 100644 index 0000000..89161bf --- /dev/null +++ b/cmd/web/handlers_util.go @@ -0,0 +1,58 @@ +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 +} -- cgit v1.2.3