github.com/blend/go-sdk@v1.20220411.3/webutil/logging_util.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package webutil
     9  
    10  import (
    11  	"fmt"
    12  	"net/http"
    13  	"sort"
    14  	"strconv"
    15  	"strings"
    16  
    17  	"github.com/blend/go-sdk/ansi"
    18  	"github.com/blend/go-sdk/logger"
    19  )
    20  
    21  // FormatHeaders formats headers for output.
    22  // Header keys will be printed in alphabetic order.
    23  func FormatHeaders(tf logger.TextFormatter, keyColor ansi.Color, header http.Header) string {
    24  	var keys []string
    25  	for key := range header {
    26  		keys = append(keys, key)
    27  	}
    28  	sort.Strings(keys)
    29  
    30  	var values []string
    31  	for _, key := range keys {
    32  		values = append(values, fmt.Sprintf("%s:%s", tf.Colorize(key, keyColor), header.Get(key)))
    33  	}
    34  	return "{ " + strings.Join(values, " ") + " }"
    35  }
    36  
    37  // ColorizeByStatusCode returns a value colored by an http status code.
    38  func ColorizeByStatusCode(statusCode int, value string) string {
    39  	if statusCode >= http.StatusOK && statusCode < 300 { //the http 2xx range is ok
    40  		return ansi.ColorGreen.Apply(value)
    41  	} else if statusCode == http.StatusInternalServerError {
    42  		return ansi.ColorRed.Apply(value)
    43  	}
    44  	return ansi.ColorYellow.Apply(value)
    45  }
    46  
    47  // ColorizeByStatusCodeWithFormatter returns a value colored by an http status code with a given formatter.
    48  func ColorizeByStatusCodeWithFormatter(tf logger.TextFormatter, statusCode int, value string) string {
    49  	if statusCode >= http.StatusOK && statusCode < 300 { //the http 2xx range is ok
    50  		return tf.Colorize(value, ansi.ColorGreen)
    51  	} else if statusCode == http.StatusInternalServerError {
    52  		return tf.Colorize(value, ansi.ColorRed)
    53  	}
    54  	return tf.Colorize(value, ansi.ColorYellow)
    55  }
    56  
    57  // ColorizeStatusCode colorizes a status code.
    58  func ColorizeStatusCode(statusCode int) string {
    59  	return ColorizeByStatusCode(statusCode, strconv.Itoa(statusCode))
    60  }
    61  
    62  // ColorizeStatusCodeWithFormatter colorizes a status code with a given formatter.
    63  func ColorizeStatusCodeWithFormatter(tf logger.TextFormatter, statusCode int) string {
    64  	return ColorizeByStatusCodeWithFormatter(tf, statusCode, strconv.Itoa(statusCode))
    65  }