github.com/vmware/transport-go@v1.3.4/plank/utils/bytes.go (about)

     1  // Copyright 2019-2021 VMware, Inc.
     2  // SPDX-License-Identifier: BSD-2-Clause
     3  
     4  package utils
     5  
     6  import (
     7  	"encoding/json"
     8  	"strings"
     9  )
    10  
    11  // ConvertInterfaceToByteArray converts the interface i into a byte array. Depending on the
    12  // value of mimeType being of JSON type, either JSON Marshaller is used or the interface is
    13  // just straight cast to a byte array.
    14  func ConvertInterfaceToByteArray(mimeType string, i interface{}) (results []byte, err error) {
    15  	// use JSON Marshaller for application/json mime type
    16  	if strings.Contains(mimeType, "json") {
    17  		results, err = json.Marshal(i)
    18  		return
    19  	}
    20  
    21  	// for the rest mime types, cast the original data format to a byte array
    22  	switch i.(type) {
    23  	case string:
    24  		results = []byte(i.(string))
    25  		break
    26  	default:
    27  		results = i.([]byte)
    28  	}
    29  	return
    30  }