[Golang] dealing with arrays: gqlgen with go-pg

Be careful for difference between JSON array and pg array

Jason Choi
2 min readDec 7, 2020

Problem.

When you defined User type like this on schema.graphqls

type User { ID: String! profileImages: [String]}

And after you generate by

go run github.com/99designs/gqlgen generate

There comes the generated model like this in models_gen.go:

type User struct {  ID string `json:”ID”`  ProfileImages []string`json:”profileImages”`}

And if you define CreateUser function like this in schema.resolvers.go, as usual

func CreateUser (profileImages []string) {  user := &model.User{    ID: uuid.New().String(),    ProfileImages: profileImages,}
}

There comes an error with this Mutation.

mutation { createUser(profileImages: [ “url1”, “url2” ]) {  ID}}

Error: malformed array literal

So, let’s see what happened.

Reason

The error happened because structs and slices are marshaled as JSON as described here. The array field of the model(‘profileImages’ here) should be added pg:,array tag, not JSON tag, but auto generated model by gqlgen generate can only have JSON tag.

Postgres array’s form is {“a”, “b”}, whereas the json array’s form is [“a”, “b”], and that makes the array literal malformed.

How to solve

I made custom models for User myself, not auto-generated by gqlgen generate.

// at root/graph/model/user.gopackage model// User typetype User struct { ID string `json:”ID”` ProfileImages []string `pg:”,array”`}

Then, I told gqlgen that I will use User model that I made myself, not automatically generated by gqlgen. You can refer here for more explanation.

// at gqlgen.ymlmodels:ID:model:- github.com/99designs/gqlgen/graphql.ID
- blah blah
Int:model:- github.com/99designs/gqlgen/graphql.Int- blah blahUser:model:- github.com/jason150/my_project/graph/model.User

Now, ProfileImages field of User model can be converted to postgres array safely, and no error occurs.

--

--