Golang : Remove / Hide fields from a Golang struct

Below golang program hides / removes parameters from a Go struct before printing it.


Go ( Golang ) : Hide fields from a struct

package main

import (
	"fmt"
	"encoding/json"
)

type Profile struct {
	Name   string
	Mobile string
	City   string
	// Hide the below parameters while printing the structure
	Password string
	Token    string
}

func PrintProfile(params interface{}, msg string, hideParams []string) {

	var profileMap map[string]interface{}

	byteSlice, _ := json.Marshal(params)

	err := json.Unmarshal(byteSlice, &profileMap)
	if err != nil {
		fmt.Println("Failed to unmarshal JSON params while printing profile")
		return
	}

	for _, param := range hideParams {
		delete(profileMap, param)
	}

	fmt.Println(msg, "Profile :", fmt.Sprintf("%+v", profileMap))
}

func main() {

	p := Profile{"John Dick",
		"8888899999",
		"NewPork",
		"DoggyLove",
		"TokenLove"}

	var hideParams = []string{"Password", "Token"}

	PrintProfile(p, "Detail of John Dick", hideParams)
}

Output

Detail of John Dick Profile : map[City:NewPork Mobile:8888899999 Name:John Dick]


Copyright (c) 2019-2024, Algotree.org.
All rights reserved.