github.com/Comcast/plax@v0.8.32/dsl/util.go (about)

     1  /*
     2   * Copyright 2021 Comcast Cable Communications Management, LLC
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   * http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   *
    16   * SPDX-License-Identifier: Apache-2.0
    17   */
    18  
    19  package dsl
    20  
    21  import (
    22  	"encoding/json"
    23  	"fmt"
    24  	"strings"
    25  
    26  	"github.com/Comcast/plax/subst"
    27  )
    28  
    29  func JSON(x interface{}) string {
    30  	js, err := subst.JSONMarshal(&x)
    31  	if err != nil {
    32  		js, _ = subst.JSONMarshal(map[string]interface{}{
    33  			fmt.Sprintf("%T", x): fmt.Sprintf("%#v", x),
    34  		})
    35  	}
    36  	return string(js)
    37  }
    38  
    39  func MaybeParseJSON(x interface{}) interface{} {
    40  	if s, is := x.(string); is {
    41  		var y interface{}
    42  		if err := json.Unmarshal([]byte(s), &y); err == nil {
    43  			return y
    44  		}
    45  	}
    46  	return x
    47  }
    48  
    49  func MaybeSerialize(x interface{}) (string, error) {
    50  	if s, is := x.(string); is {
    51  		return s, nil
    52  	}
    53  	js, err := json.Marshal(&x)
    54  	if err != nil {
    55  		// We still return something useful, but we also
    56  		// return the error.  Probably dumb.
    57  		return JSON(map[string]interface{}{
    58  			"error": err.Error(),
    59  			"on":    fmt.Sprintf("%#v", x),
    60  		}), err
    61  	}
    62  	return string(js), nil
    63  }
    64  
    65  // Canon constructs a canonical (via JSON) representation.
    66  func Canon(x interface{}) interface{} {
    67  	js, err := json.Marshal(&x)
    68  	if err != nil {
    69  		panic(err)
    70  	}
    71  	var y interface{}
    72  	if err = json.Unmarshal(js, &y); err != nil {
    73  		panic(err)
    74  	}
    75  	return y
    76  }
    77  
    78  // short returns a short version of the given string.
    79  func short(s string) string {
    80  	limit := 30
    81  	s = strings.ReplaceAll(s, "\n", " ")
    82  	if limit < len(s)-3 {
    83  		return s[0:limit] + "..."
    84  	}
    85  	return s
    86  }
    87  
    88  // As is shameful.
    89  func As(src interface{}, dst interface{}) error {
    90  	js, err := json.Marshal(&src)
    91  	if err != nil {
    92  		return err
    93  	}
    94  	return json.Unmarshal(js, &dst)
    95  }