-
Notifications
You must be signed in to change notification settings - Fork 0
/
version.go
71 lines (58 loc) · 1.55 KB
/
version.go
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
59
60
61
62
63
64
65
66
67
68
69
70
71
package version
import (
"crypto/md5"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
// Interface that returns version information.
type Versioner interface {
GetVersion() string
}
type versionService struct {
Version string `json:"version"`
Checksum string `json:"checksum"`
}
func New(v Versioner) *http.ServeMux {
service := &versionService{Version: v.GetVersion(), Checksum: GetChecksum()}
return service.registerRoutes()
}
func (v *versionService) registerRoutes() *http.ServeMux {
mux := http.NewServeMux()
mux.Handle("/version", CorsHandler(v))
return mux
}
func (v *versionService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(v)
}
func GetChecksum() string {
file, err := os.Open(os.Args[0])
if err != nil {
return "Error getting checksum"
}
defer file.Close()
//expensive, but the hit is once on start and our binaries are small
hash := md5.New()
if _, err := io.Copy(hash, file); err != nil {
return "Error getting checksum"
}
var result []byte
return fmt.Sprintf("%x", hash.Sum(result))
}
func CorsHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET")
}
// Stop here if its Preflighted OPTIONS request
if r.Method == "OPTIONS" {
return
}
next.ServeHTTP(w, r)
})
}