github.com/lulzWill/go-agent@v2.1.2+incompatible/internal/utilities.go (about)

     1  package internal
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"net/http"
     7  	"strconv"
     8  	"strings"
     9  	"time"
    10  )
    11  
    12  // JSONString assists in logging JSON:  Based on the formatter used to log
    13  // Context contents, the contents could be marshalled as JSON or just printed
    14  // directly.
    15  type JSONString string
    16  
    17  // MarshalJSON returns the JSONString unmodified without any escaping.
    18  func (js JSONString) MarshalJSON() ([]byte, error) {
    19  	if "" == js {
    20  		return []byte("null"), nil
    21  	}
    22  	return []byte(js), nil
    23  }
    24  
    25  func removeFirstSegment(name string) string {
    26  	idx := strings.Index(name, "/")
    27  	if -1 == idx {
    28  		return name
    29  	}
    30  	return name[idx+1:]
    31  }
    32  
    33  func timeToFloatSeconds(t time.Time) float64 {
    34  	return float64(t.UnixNano()) / float64(1000*1000*1000)
    35  }
    36  
    37  func timeToFloatMilliseconds(t time.Time) float64 {
    38  	return float64(t.UnixNano()) / float64(1000*1000)
    39  }
    40  
    41  func floatSecondsToDuration(seconds float64) time.Duration {
    42  	nanos := seconds * 1000 * 1000 * 1000
    43  	return time.Duration(nanos) * time.Nanosecond
    44  }
    45  
    46  func absTimeDiff(t1, t2 time.Time) time.Duration {
    47  	if t1.After(t2) {
    48  		return t1.Sub(t2)
    49  	}
    50  	return t2.Sub(t1)
    51  }
    52  
    53  func compactJSON(js []byte) []byte {
    54  	buf := new(bytes.Buffer)
    55  	if err := json.Compact(buf, js); err != nil {
    56  		return nil
    57  	}
    58  	return buf.Bytes()
    59  }
    60  
    61  // CompactJSONString removes the whitespace from a JSON string.
    62  func CompactJSONString(js string) string {
    63  	out := compactJSON([]byte(js))
    64  	return string(out)
    65  }
    66  
    67  // GetContentLengthFromHeader gets the content length from a HTTP header, or -1
    68  // if no content length is available.
    69  func GetContentLengthFromHeader(h http.Header) int64 {
    70  	if cl := h.Get("Content-Length"); cl != "" {
    71  		if contentLength, err := strconv.ParseInt(cl, 10, 64); err == nil {
    72  			return contentLength
    73  		}
    74  	}
    75  
    76  	return -1
    77  }
    78  
    79  // StringLengthByteLimit truncates strings using a byte-limit boundary and
    80  // avoids terminating in the middle of a multibyte character.
    81  func StringLengthByteLimit(str string, byteLimit int) string {
    82  	if len(str) <= byteLimit {
    83  		return str
    84  	}
    85  
    86  	limitIndex := 0
    87  	for pos := range str {
    88  		if pos > byteLimit {
    89  			break
    90  		}
    91  		limitIndex = pos
    92  	}
    93  	return str[0:limitIndex]
    94  }