在Golang中,你可以将用户对象设置为nil来表示null(JSON中的null)。

huangapple go评论127阅读模式
英文:

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

问题

我正在使用Golang编写一些身份验证代码,并且我有以下代码,如果UserID不为nil,则填充UserResponse,但是当UserID为nil时,发送的UserResponse看起来像这样:

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

我的代码是:

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")
}
英文:

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")
}

答案1

得分: 2

应该是这样的:

{
    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)
}
英文:

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)
}

答案2

得分: 0

我找到了一个解决方案。首先,我创建了一个interface{},根据UserID是否存在,将其设置为nil或者一个用户对象。然而,我想要一个更好、更清晰的解决方案,于是我想出了以下代码:

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)
}

请注意,这只是一个示例代码,具体实现可能需要根据你的需求进行调整。

英文:

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)
	}

huangapple
  • 本文由 发表于 2022年4月8日 05:49:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/71789314.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定