How to append custom attribute to Golang struct like $append on a Laravel model?

Issue

I am trying to add a custom attribute to my Golang struct just like how I usually add custom attribute on a Laravel model using the $appends variable.

This is the code:

package models

import (
    "time"
)

type Dummy struct {
    ID          string `json:"id" gorm:"primary_key"`
    Description string `json:"description"`
    Image       string `json:"image"`
    ImageUrl    ImageUrlDummy
    Number      int       `json:"number"`
    UserId      string    `json:"user_id"`
    User        User      `json:"user"`
    CreatedAt   time.Time `json:"created_at"`
    UpdatedAt   time.Time `json:"updated_at"`
}

func ImageUrlDummy() string {
    return "test"
}

However, the ImageUrlDummy inside the struct does not work, it return error such as:


ImageUrlDummy (value of type func() string) is not a type

How do I achieve this same code from Laravel to Golang?

class Dummy extends Model
{
    protected $appends = ['image_url'];

    public function getImageUrlAttribute(){
        return "this is the image url";
    }
}

Please pardon me I am still learning Golang, thank you

Solution

You are not far off..

Change your struct to (remove ImageUrlDummy, fix json tag for Image):

    type Dummy struct {
        ID          string `json:"id" gorm:"primary_key"`
        Description string `json:"description"`
        Image       string `json:"image"`
        Number      int       `json:"number"`
        UserId      string    `json:"user_id"`
        User        User      `json:"user"`
        CreatedAt   time.Time `json:"created_at"`
        UpdatedAt   time.Time `json:"updated_at"`
    }

Then define a method with a receiver of type Dummy pointer

    func (d *Dummy) ImageUrl() string {
        return "test"
    }

Example with a few more things: https://play.golang.com/p/olGSFhBgqkG

Answered By – sbrichards

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.