简体   繁体   中英

How do I append to all string values inside a struct?

I have a struct defined in fruits.go

package domain

type AppleImages struct {
    Front string `json:"frontImage"`
    Back  string `json:"backImage"`
    Top   string `json:"topImage"`
}

And I defined the same in process.go (which returns this data to the handler). This definition is only for demonstration purposes since I'm getting values from the database using gorm so we cannot append the required URL here.

package process

func getApple() (apple domain.Apple){
    apple = domain.Apple{
        Front: "front-image.png"
        Back: "back-image.png"
        Top: "top-image.png"
    }
    return
}

For my output is want to return

{
    frontImage: "https://www.example.com/front-image.png",
    backImage: "https://www.example.com/back-image.png",
    topImage: "https://www.example.com/top-image.png",
}

I don't want to manually add https://www.example.com/ to each of the images in the struct.

Is there a way of parsing through the struct and automatically appending this string to all existing values?

Use gorm AfterFind hook. Every time after load data from database gorm call AfterFind and your data will be updated for Apple model. Then you don't need to manually do it after every time fetching from the database.

func (u *Apple) AfterFind() (err error) {
  u.Front= "https://www.example.com/"+ u.Front
  u.Back= "https://www.example.com/"+ u.Back
  u.Top= "https://www.example.com/"+ u.Top
  return
}

See details here

Is there a way of parsing through the struct and automatically appending this string to all existing values?

No.

I don't want to manually add https://www.example.com/ to each of the images in the struct.

Go provides no magic for thing to happen without you programming it. You must do this "manually".

You could use reflect to add a prefix for each filed in the struct. See details here .

func getApple() (apple domain.Apple) {
    apple = domain.Apple{
        Front: "front-image.png",
        Back:  "back-image.png",
        Top:   "top-image.png",
    }
    addURL(&apple, "https://www.example.com/")
    //fmt.Println(apple)
    return
}

func addURL(apple *domain.Apple, url string) {
    structValue := reflect.ValueOf(apple).Elem()
    for i := 0; i < structValue.NumField(); i++ {
        fieldValue := structValue.Field(i)

        // skip non-string field
        if fieldValue.Type().Kind() != reflect.String {
            continue
        }

        structValue.Field(i).SetString(url + fieldValue.String())
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM