I'm just making my own backend with Labstack Echo for fun and I'm not sure how to handle the null values from MySQL. I'm using NullString but when I want to return the JSON I can't return the same struct I scanned in because email and courseId are not strings, they are NullString.
[
{
"uid": "1",
"name": "Yumiko",
"email": {
"String": "",
"Valid": false
},
"cid": {
"String": "",
"Valid": false
}
}
]
Do I have to make another struct to fill in and return after null checking all the columns?
This is how I'm doing it right now, removed all the err checks to reduce size
func GetUsers(c echo.Context) error {
rows, err := model.DB.Query("SELECT * FROM users")
var a []model.User
u := new(model.User)
columns, err := rows.Columns()
values := make([]sql.RawBytes, len(columns))
scanArgs := make([]interface{}, len(values))
for i := range values {
scanArgs[i] = &values[I]
}
for rows.Next() {
err = rows.Scan(scanArgs...)
err = rows.Scan(&u.UserId, &u.Name, &u.Email, &u.CourseId)
a = append(a, *u)
}
return c.JSON(http.StatusOK, a)
}
And User is
type User struct {
UserId int `json:"uid" xml:"uid" form:"uid" query:"uid"`
Name string `json:"name" xml:"name" form:"name" query:"name"`
Email sql.NullString `json:"email" xml:"email" form:"email" query:"email"`
CourseId sql.NullString `json:"cid" xml:"cid" form:"cid" query:"cid"`
}
I want to improve and implement the best practices thanks, also considering scrapping all this and going with gorm.