首页 > 其他分享 >go 语言jsontoYAML

go 语言jsontoYAML

时间:2023-01-11 14:23:07浏览次数:37  
标签:return 语言 err nil will interface jsontoYAML go string

/*
Copyright The Helm Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// since funcMap is non-importable function, just copy/paste file:)

package template

// nosemgrep: go.lang.security.audit.xss.import-text-template.import-text-template
import (
"bytes"
"encoding/binary"
"encoding/json"
"fmt"
"net"
"strings"
"text/template"

"github.com/BurntSushi/toml"
"github.com/Masterminds/sprig/v3"
"sigs.k8s.io/yaml"
)

// funcMap returns a mapping of all of the functions that Engine has.
func funcMap() template.FuncMap {
f := sprig.TxtFuncMap()
// delete(f, "env")
// delete(f, "expandenv")

// Add some extra functionality
extra := template.FuncMap{
"toToml": toTOML,
"toYaml": toYAML,
"fromYaml": fromYAML,
"fromYamlArray": fromYAMLArray,
"toJson": toJSON,
"fromJson": fromJSON,
"fromJsonArray": fromJSONArray,
"ipNet": ipNet,
"ipAt": ipAt,
}

for k, v := range extra {
f[k] = v
}

return f
}

// toYAML takes an interface, marshals it to yaml, and returns a string. It will
// always return a string, even on marshal error (empty string).
//
// This is designed to be called from a template.
func toYAML(v interface{}) string {
data, err := yaml.Marshal(v)
if err != nil {
// Swallow errors inside of a template.
return ""
}
return strings.TrimSuffix(string(data), "\n")
}

// fromYAML converts a YAML document into a map[string]interface{}.
//
// This is not a general-purpose YAML parser, and will not parse all valid
// YAML documents. Additionally, because its intended use is within templates
// it tolerates errors. It will insert the returned error message string into
// m["Error"] in the returned map.
func fromYAML(str string) map[string]interface{} {
m := map[string]interface{}{}

if err := yaml.Unmarshal([]byte(str), &m); err != nil {
m["Error"] = err.Error()
}
return m
}

// fromYAMLArray converts a YAML array into a []interface{}.
//
// This is not a general-purpose YAML parser, and will not parse all valid
// YAML documents. Additionally, because its intended use is within templates
// it tolerates errors. It will insert the returned error message string as
// the first and only item in the returned array.
func fromYAMLArray(str string) []interface{} {
a := []interface{}{}

if err := yaml.Unmarshal([]byte(str), &a); err != nil {
a = []interface{}{err.Error()}
}
return a
}

// toTOML takes an interface, marshals it to toml, and returns a string. It will
// always return a string, even on marshal error (empty string).
//
// This is designed to be called from a template.
func toTOML(v interface{}) string {
b := bytes.NewBuffer(nil)
e := toml.NewEncoder(b)
if err := e.Encode(v); err != nil {
return err.Error()
}
return b.String()
}

// toJSON takes an interface, marshals it to json, and returns a string. It will
// always return a string, even on marshal error (empty string).
//
// This is designed to be called from a template.
func toJSON(v interface{}) string {
data, err := json.Marshal(v)
if err != nil {
// Swallow errors inside of a template.
return ""
}
return string(data)
}

// fromJSON converts a JSON document into a map[string]interface{}.
//
// This is not a general-purpose JSON parser, and will not parse all valid
// JSON documents. Additionally, because its intended use is within templates
// it tolerates errors. It will insert the returned error message string into
// m["Error"] in the returned map.
func fromJSON(str string) map[string]interface{} {
m := make(map[string]interface{})

if err := json.Unmarshal([]byte(str), &m); err != nil {
m["Error"] = err.Error()
}
return m
}

// fromJSONArray converts a JSON array into a []interface{}.
//
// This is not a general-purpose JSON parser, and will not parse all valid
// JSON documents. Additionally, because its intended use is within templates
// it tolerates errors. It will insert the returned error message string as
// the first and only item in the returned array.
func fromJSONArray(str string) []interface{} {
a := []interface{}{}

if err := json.Unmarshal([]byte(str), &a); err != nil {
a = []interface{}{err.Error()}
}
return a
}

func ipNet(s string) string {
_, ipv4Net, err := net.ParseCIDR(s)
if err != nil {
return fmt.Sprintf("invalid cidr: %s", err)
}
return ipv4Net.String()
}

func ipAt(s string, idx uint32) string {
_, ipv4Net, err := net.ParseCIDR(s)
if err != nil {
return fmt.Sprintf("invalid cidr: %s", err)
}
mask := binary.BigEndian.Uint32(ipv4Net.Mask)
start := binary.BigEndian.Uint32(ipv4Net.IP)
finish := (start & mask) | (mask ^ 0xffffffff)
if start+idx > finish {
return "out of ip address range"
}
ip := make(net.IP, 4)
binary.BigEndian.PutUint32(ip, start+idx)
return ip.String()
}

标签:return,语言,err,nil,will,interface,jsontoYAML,go,string
From: https://www.cnblogs.com/cheyunhua/p/17043573.html

相关文章

  • 哪些软件和程序用了C语言?
    在日常生活中,很多系统软件和桌面应用程序都采用C语言进行开发,下面给出了一些示例。1.操作系统UNIX是第一个使用**语言设计的操作系统,它使用的编程语言就是C语言。后来,Mic......
  • Sentinel Go-毫秒级统计数据结构揭秘
    作者:binbin0325背景介绍随着微服务的流行,服务和服务之间的稳定性变得越来越重要。在2020年,Sentinel社区推出SentinelGo版本,朝着云原生方向演进。SentinelGo是一......
  • windows golang 多版本管理
    下载g软件包源代码链接  https://github.com/voidint/g  二进制包连接 https://github.com/voidint/g/releases在%USERFILE%目录下.g目录创建把解压出来的g.e......
  • 一个C语言的剪刀石头布小游戏
    /******************************************************石头剪刀布的程序geek_monkey于2015年3月3日修改了bug(输入字符非石头剪刀布都算是玩家赢)编译环境为VC+......
  • Linux 系统中搭建Beego开发环境
    工欲善其事必先利其器。在gopath的上一级目录执行gomodinitgithub.com/beego进入到gopath路径下执行 goget-ugithub.com/beego/beego/v2和 goget-ugithub.c......
  • Docker学习笔记:login、logout登录登出
    一、login登录dockerlogin登陆到一个Docker镜像仓库,如果未指定镜像仓库地址,默认为官方仓库DockerHub。#语法dockerlogin[OPTIONS][SERVER]Options:-p,-......
  • typroa和picgo-gitee图床简单配置以及常用快捷键
    目录简介安装for-linux插件picgo-gitee图床1.软件下载安装1.1安装picgo1.2安装nodejs1.3安装picgo-core1.4安装flameshot(截图工具,非必要)1.5安装xclip2.搭建gitee......
  • C++_语言概览和资料
    C++C语言1969年-1973年完成,其出发点是为了编写Unix操作系统设计目标需求、背景和待解决问题 演化过程中,来自用户的反馈和语言实现者们积累的经验设计哲学:高效......
  • 防微杜渐,未雨绸缪,百度网盘(百度云盘)接口API自动化备份上传以及开源发布,基于Golang
    奉行长期主义的开发者都有一个共识:对于服务器来说,数据备份非常重要,因为服务器上的数据通常是无价的,如果丢失了这些数据,可能会导致严重的后果,伴随云时代的发展,备份技术也让......
  • (7)go-micro微服务zap日志配置
    目录一Zap日志介绍二Zap日志安装三Zap日志初始化四Zap日志重写方法五Zap日志使用六最后一Zap日志介绍Zap是在Go中实现超快、结构化、分级的日志记录。Zap......