Go小工具系列——型別轉換

ConnorK 發表於 2021-03-25
Go

struct to map

// struct to map
func Struct2Map(obj interface{}) map[string]interface{} {
    var ret map[string]interface{}
    jsonStr, _ := json.Marshal(obj)
    err := json.Unmarshal(jsonStr, &ret)
    if err != nil {
        panic("struct to map error")
    }
    return ret
}

map to xml

import (
    "github.com/flosch/pongo2/v4"
)

// map to xml
func Map2xml(inputMap map[string]interface{}, droolsName string) string {
    for k, v := range inputMap {
        switch v.(type) {
        case float64:
            inputMap[k] = strconv.FormatFloat(v.(float64), 'f', -1, 64)
        default:
            inputMap[k] = fmt.Sprintf("%v", v)
        }
    }

    tpl, _ := pongo2.FromFile(droolsPath)
    out, _ := tpl.Execute(inputMap)

    return out
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結