istio

Форк
0
/
home.go 
95 строк · 2.5 Кб
1
// Copyright Istio Authors
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14

15
package ctrlz
16

17
import (
18
	"html/template"
19
	"net/http"
20
	"os"
21
	"path/filepath"
22
	"runtime"
23
	"strings"
24
	"time"
25

26
	"github.com/gorilla/mux"
27

28
	"istio.io/istio/pkg/ctrlz/assets"
29
	"istio.io/istio/pkg/ctrlz/fw"
30
)
31

32
var mimeTypes = map[string]string{
33
	".css": "text/css; charset=utf-8",
34
	".svg": "image/svg+xml; charset=utf-8",
35
	".ico": "image/x-icon",
36
	".png": "image/png",
37
	".js":  "application/javascript",
38
}
39

40
type homeInfo struct {
41
	ProcessName string
42
	HeapSize    uint64
43
	NumGC       uint32
44
	CurrentTime int64
45
	Hostname    string
46
	IP          string
47
}
48

49
func getHomeInfo() *homeInfo {
50
	var ms runtime.MemStats
51
	runtime.ReadMemStats(&ms)
52

53
	hostName, _ := os.Hostname()
54

55
	return &homeInfo{
56
		ProcessName: os.Args[0],
57
		HeapSize:    ms.HeapAlloc,
58
		NumGC:       ms.NumGC,
59
		CurrentTime: time.Now().UnixNano(),
60
		Hostname:    hostName,
61
		IP:          getLocalIP(),
62
	}
63
}
64

65
func registerHome(router *mux.Router, layout *template.Template) {
66
	homeTmpl := assets.ParseTemplate(template.Must(layout.Clone()), "templates/home.html")
67
	errorTmpl := assets.ParseTemplate(template.Must(layout.Clone()), "templates/404.html")
68

69
	_ = router.NewRoute().PathPrefix("/").Methods("GET").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
70
		if req.URL.Path == "/" {
71
			// home page
72
			fw.RenderHTML(w, homeTmpl, getHomeInfo())
73
		} else if req.URL.Path == "/homej" || req.URL.Path == "/homej/" {
74
			fw.RenderJSON(w, http.StatusOK, getHomeInfo())
75
		} else if a, err := assets.FS.ReadFile("static" + req.URL.Path); err == nil {
76
			// static asset
77
			ext := strings.ToLower(filepath.Ext(req.URL.Path))
78
			if mime, ok := mimeTypes[ext]; ok {
79
				w.Header().Set("Content-Type", mime)
80
			}
81
			_, _ = w.Write(a)
82
		} else {
83
			// 'not found' page
84
			w.WriteHeader(http.StatusNotFound)
85
			fw.RenderHTML(w, errorTmpl, nil)
86
		}
87
	})
88

89
	_ = router.NewRoute().Methods("PUT").Path("/homej/exit").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
90
		w.WriteHeader(http.StatusAccepted)
91
		time.AfterFunc(1*time.Second, func() {
92
			os.Exit(0)
93
		})
94
	})
95
}
96

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.