mailerlite / mailerlite-go

Go SDK for MailerLite
MIT License
3 stars 3 forks source link

Error when trying to add new Subscriber #17

Open eclane opened 1 year ago

eclane commented 1 year ago

Hello, I am trying to add a new subscriber using go and gin-gonic, but I keep getting an error

"error": "POST https://connect.mailerlite.com/api/subscribers: 422 The groups field must be an array. map[groups:[The groups field must be an array.]]",

Here is my code

var MAILERLITE_API = os.Getenv("MAILERLITE_API")
func SaveNewsletter() gin.HandlerFunc {
    return func(c *gin.Context) {
        client := mailerlite.NewClient(MAILERLITE_API)
        ctx := context.TODO()
        subscriber := &mailerlite.Subscriber{
            Email: "example@gmail.com",
            Fields: map[string]interface{}{
                "city": "Vilnius",
            },
        }
        newSubscriber, _, err := client.Subscriber.Create(ctx, subscriber)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": err.Error()})
            return
        }
        log.Println(err, newSubscriber)
        c.JSON(http.StatusOK, gin.H{
            "success":    true,
            "subscriber": newSubscriber.Data,
        })

    }
}
agparadiso commented 1 year ago

If you don't need to add groups you can probably make it work by adding: Groups: []mailerlite.Group{}, like this:

subscriber := &mailerlite.Subscriber{
            Email: "example@gmail.com",
            Fields: map[string]interface{}{
                "city": "Vilnius",
            },
            Groups: []mailerlite.Group{},
        }

If you need to add groups like Im trying to do now, this won't work because the api is expecting a list of strings instead of a list of mailerlite.Group{}. Probably a new struct should be created for the creation of subscribers

robgordon89 commented 4 months ago

open to PR's to fix this 👍

robgordon89 commented 4 months ago

you can now submit this without groups, im trying to think of the best way to handle subscriber groups 🤔 i would hate to have to introduce a new type just for this NewSubscriber for example