I am newbie. I have a image
in my db which is stored as a path
to it. In api json I have to output this path and add a prefix
in front of it, how can I do that?
My function:
func GetAllSliders(c *gin.Context) {
var sliders models.Slider
config.DB.Model(models.Slider{}).Where("id=?", 1).Update("image", ("https://spares-dt.ru/" + models.Slider{}.Image)) //i tried this, but it doesnt work
if err := config.DB.Find(&sliders).Error; err != nil {
c.JSON(http.StatusInternalServerError, err.Error())
} else {
c.JSON(http.StatusOK, gin.H{"data": sliders})
}
}
Json output i have:
{
"data": {
"id": 1,
"main_text": "123",
"upper_text": "123",
"down_text": "123",
"image": "data/photos/sliders/image.PNG"
}
}
I want:
{
"data": {
"id": 1,
"main_text": "123",
"upper_text": "123",
"down_text": "123",
"image": "https://spakes-dt.ru/data/photos/sliders/image.PNG"
}
}
And my struct:
type Slider struct {
Id uint `json:"id" gorm:"primaryKey"`
MainText string `json:"main_text"`
UpperText string `json:"upper_text"`
DownText string `json:"down_text"`
Image string `json:"image"`
}
Simply change the Image
field's value before JSON marshaling it:
if err := config.DB.Find(&sliders).Error; err != nil {
c.JSON(http.StatusInternalServerError, err.Error())
} else {
sliders.Image = "https://spares-dt.ru/" + sliders.Image
c.JSON(http.StatusOK, gin.H{"data": sliders})
}