istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/ctrlz/fw/utils.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 fw
    16  
    17  import (
    18  	"bytes"
    19  	"encoding/json"
    20  	"fmt"
    21  	"html/template"
    22  	"net/http"
    23  )
    24  
    25  // RenderError outputs an error message
    26  func RenderError(w http.ResponseWriter, statusCode int, err error) {
    27  	w.WriteHeader(statusCode)
    28  	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    29  	_, _ = fmt.Fprintf(w, "%v", err)
    30  }
    31  
    32  // RenderHTML executes the given template, sending the output to the supplied response writer
    33  func RenderHTML(w http.ResponseWriter, t *template.Template, data any) {
    34  	b := &bytes.Buffer{}
    35  
    36  	if err := t.Execute(b, data); err != nil {
    37  		RenderError(w, http.StatusInternalServerError, err)
    38  		return
    39  	}
    40  
    41  	w.WriteHeader(http.StatusOK)
    42  	w.Header().Set("Content-Type", "text/html; charset=utf-8")
    43  	_, _ = b.WriteTo(w)
    44  }
    45  
    46  // RenderJSON outputs the given data as JSON
    47  func RenderJSON(w http.ResponseWriter, statusCode int, data any) {
    48  	w.WriteHeader(statusCode)
    49  	w.Header().Set("Content-Type", "application/json; charset=utf-8")
    50  
    51  	if err := json.NewEncoder(w).Encode(data); err != nil {
    52  		RenderError(w, http.StatusInternalServerError, err)
    53  	}
    54  }