Derek
Derek

Reputation: 12378

Creating an interface for a JSON struct in golang

Say I have a struct that I bind json param data to like

type User struct {
  FirstName string `json:"firstName"`
}

The attribute FirstName has to be capitalized so that the json values can be binded to the struct.

But I also want to create an interface to accept any struct that has a FirstName like attribute. Since FirstName is already capitalized and taken, I have to name the method something else.

type NameInterface interface {
    FirstName() string // nope
    FirstNameValue() string // maybe?
}

But it seems really weird to have to add a helper function for each attribute on all my json structs just so they can work with an interface. Is there something I'm misunderstanding or a programming pattern I'm missing? What is the best way to get a json struct to work with interfaces in go?

More (what I am trying to do):

I want to parse json params that are coming from my controllers into structs. And then pass that struct data into filters which then run sql commands to filter data based on the params data. I wanted to use interfaces so I can pass in structs created from different sources into my filters.

Upvotes: 0

Views: 1533

Answers (1)

LemurFromTheId
LemurFromTheId

Reputation: 4281

Interfaces in Go specify behaviour, but you're trying to use them to describe data. This is why you're finding your approach to be difficult - and it's also why it's probably the wrong approach.

It's difficult to give a more specific answer without knowing what you're really trying to achieve, but if you, for example, want to be able to have functions that can read specific named fields from different struct types, you'll probably want to define one struct to describe this data and then embed that struct into other struct types.

Something like this might fit your needs:

type Person struct {
    FirstName string `json:"firstName"`
}

type User struct {
    Person
    // other User-specific fields
}

type Admin struct {
    Person
    // other Admin-specific fields
}

func Harass(p Person) { }

func main() {
    user := User{Person{"Frank"}}
    Harass(user.Person)
    admin := Admin{Person{"Angelina"}}
    Harass(admin.Person)
}

Upvotes: 2

Related Questions