Home > Blockchain >  golang ToUpper struct string fields
golang ToUpper struct string fields

Time:12-06

I have a struct like this:

type CvssV3 struct {
    BaseScore             *float32 `json:"baseScore"`
    AttackVector          *string  `json:"attackVector"`
    AttackComplexity      *string  `json:"attackComplexity"`
    PrivilegesRequired    *string  `json:"privilegesRequired"`
    UserInteraction       *string  `json:"userInteraction"`
    Scope                 *string  `json:"scope"`
    ConfidentialityImpact *string  `json:"confidentialityImpact"`
    IntegrityImpact       *string  `json:"integrityImpact"`
    AvailabilityImpact    *string  `json:"availabilityImpact"`
}
cvssV3 = CvssV3{
      "baseScore" : 4.3,
      "attackVector" : "Network",
      "attackComplexity" : "Low",
      "privilegesRequired" : "Low",
      "userInteraction" : "None",
      "scope" : "Unchanged",
      "confidentialityImpact" : "None",
      "integrityImpact" : "Low",
      "availabilityImpact" : "None"
    }

I want to ToUpper the string type values, expected result:

cvssV3 = CvssV3{
      "baseScore" : 4.3,
      "attackVector" : "NETWORK",
      "attackComplexity" : "LOW",
      "privilegesRequired" : "LOW",
      "userInteraction" : "NONE",
      "scope" : "UNCHANGED",
      "confidentialityImpact" : "NONE",
      "integrityImpact" : "LOW",
      "availabilityImpact" : "NONE"
    }

how to deal with it?

each field use strings.ToUpper is Inelegant

CodePudding user response:

Use the reflect package to upcase the string fields:

// Get a modifiable reflect value for cvssV3.
v := reflect.ValueOf(&cvssV3).Elem()
// For each field ...
for i := 0; i < v.NumField(); i   {
    f := v.Field(i)
    // If field is string, then UPPER.
    if f.Kind() == reflect.String {
        f.SetString(strings.ToUpper(f.String()))
    }
}

https://go.dev/play/p/xi7dp0ct6Ni

CodePudding user response:

You can iterate through the fields of your struct using the reflect library.

st := reflect.TypeOf(cvssV3)
for i := 0; i < st.NumField(); i   {
    field := st.Field(i)
    if reflect.TypeOf(field) ==  "string"{
        // apply toUpper
    } 
}
  •  Tags:  
  • go
  • Related