Home > database >  How do I send user object as nil (null in json) in Golang?
How do I send user object as nil (null in json) in Golang?

Time:04-08

I am writing some authentication using Golang, and I have the following code that populates the UserResponse if UserID is not nil, but when it IS nil, the sent UserResponse looks like this:

{
    "user": {
        "id": 0,
        "email": ""
    }
}

My code is

func (app *Application) init(w http.ResponseWriter, r *http.Request) {
    userID := r.Context().Value("userID")

    type UserResponse struct {
        ID int `json:"id"`
        Email string `json:"email"`
    }

    var user UserResponse

    if userID != nil {
        query := "select id, email from users where id = ?"
        row := app.Db.QueryRow(query, userID)
        err := row.Scan(&user.ID, &user.Email)
        if err != nil {
            fmt.Println(err.Error())
        }
        fmt.Println(user)
    }

    app.writeJSON(w, http.StatusOK, user, "user")
}

CodePudding user response:

it should be like this

{
    userID := r.Context().Value("userID")

    type User struct {
        ID    int    `json:"id"`
        Email string `json:"email"`
    }

    type Response struct {
        User *User `json:"user"`
    }

    var resp Response

    if userID != nil {
        user = &User{}
        query := "select id, email from users where id = ?"
        row := app.Db.QueryRow(query, userID)
        err := row.Scan(&user.ID, &user.Email)
        if err != nil {
            WriteJSON(w, http.StatusInternalServerError, resp)
            return 
        }
        resp.User = user
    }

    WriteJSON(w, http.StatusOK, resp)
}

CodePudding user response:

I found a solution. First I created an interface{} and populated it either nil or with a user depending on whether UserID is present. However, I wanted a better cleaner solution and came up with this.

    var user *UserResponse

    if userID != nil {
        user = &UserResponse{}
        query := "select id, email from users where id = ?"
        row := app.Db.QueryRow(query, userID)
        err := row.Scan(&user.ID, &user.Email)
        if err != nil {
            fmt.Println(err.Error())
        }
        fmt.Println(user)
    }

CodePudding user response:

What kind of response do you want if it's nill?

  •  Tags:  
  • go
  • Related