istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/ctrlz/topics/env.go (about)

     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 topics
    16  
    17  import (
    18  	"net/http"
    19  	"os"
    20  	"sort"
    21  	"strings"
    22  
    23  	"istio.io/istio/pkg/ctrlz/fw"
    24  	"istio.io/istio/pkg/ctrlz/topics/assets"
    25  )
    26  
    27  type envTopic struct{}
    28  
    29  // EnvTopic returns a ControlZ topic that allows visualization of process environment variables.
    30  func EnvTopic() fw.Topic {
    31  	return envTopic{}
    32  }
    33  
    34  func (envTopic) Title() string {
    35  	return "Environment Variables"
    36  }
    37  
    38  func (envTopic) Prefix() string {
    39  	return "env"
    40  }
    41  
    42  type envVar struct {
    43  	Name  string `json:"name"`
    44  	Value string `json:"value"`
    45  }
    46  
    47  func getVars() []envVar {
    48  	env := os.Environ()
    49  	sort.Strings(env)
    50  
    51  	result := []envVar{}
    52  	for _, v := range env {
    53  		eq := strings.Index(v, "=")
    54  		name := v[:eq] //nolint
    55  		value := v[eq+1:]
    56  		result = append(result, envVar{Name: name, Value: value})
    57  	}
    58  
    59  	return result
    60  }
    61  
    62  func (envTopic) Activate(context fw.TopicContext) {
    63  	tmpl := assets.ParseTemplate(context.Layout(), "templates/env.html")
    64  
    65  	_ = context.HTMLRouter().StrictSlash(true).NewRoute().Path("/").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
    66  		fw.RenderHTML(w, tmpl, getVars())
    67  	})
    68  
    69  	_ = context.JSONRouter().StrictSlash(true).NewRoute().Methods("GET").Path("/").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
    70  		fw.RenderJSON(w, http.StatusOK, getVars())
    71  	})
    72  }