0

How can I omit struct filed, in my case I login user and return response with user data and token but in this case I need to remove password field, how can I do this ?

type LoginFormData struct {
    Login    string `json:"name"`
    Password string `json:"password"`
}

data := new(LoginFormData)

if err := c.Bind(data); err != nil {
    return err
}

userData := data // omit password field

        return c.JSON(http.StatusOK, map[string]interface{}{
            "user": struct {
                Password string `json:"-"`
                *LoginFormData
            }{
                LoginFormData: userData,
                Password:      userData.Password,
            },
            "token": "slkdfj",
        })
Vitaliy
  • 21
  • 2

3 Answers3

1
  1. Add new struct than describe desired struct
type LoginFormResponse struct {
    Login    string `json:"name"`
    Password string `json:"-"`
}
  1. Convert
return c.JSON(http.StatusOK, map[string]interface{}{
            "user":  LoginFormResponse(*data),
            "token": "slkdfj",
        })
Vitaliy
  • 21
  • 2
0

you can create a helper package to handle api response

for example: helper/response_formatter.go:

package helper

type Response struct {
    Message string `json:"message"`
    Data interface{} `json:"data"`
}

func ResponseFormatter(message string, data interface{}) Response {
    response := Response{
        Message: message
        Data: data,
    }

    return response
}

then in echo handler:

response := helper.ResponseFormatter("authenticated", userData)

return c.JSON(http.StatusOK, response)
0

I think you're trying to resolve the problem in the wrong way.

The best practice when constructing an API is to have 2 structs for this. One for the request fields, one for the response fields. Like this:

type LoginFormReq struct {
    Login    string `json:"name"`
    Password string `json:"password"`
}

type LoginFormResp struct {
    Login    string `json:"name"`
    Password string `json:"-"`
}

This can sometimes lead to a lot of copying of data between structs, but that is kinda normal on Go development with proper separation of concerns. I usually use https://github.com/jinzhu/copier to handle this. It's a great library!