aboutsummaryrefslogtreecommitdiff
path: root/cmd/web/handlers_util.go
blob: 89161bf12b44463f9c53571f78f6c15d84e9cfbb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
}