I have nullable variables I'm trying to use in my app, and also send to a database which has columns that are default null.
This is a sample struct:
// Location type
type Location struct {
ID int `schema:"id"`
Title *string `schema:"title"`
}
Title is defined as *string, as it could be null (e.g. no user input or client app sends it as null).
Here’s my function receiving form data:
// JSONLocationCreate func
func (a *App) JSONLocationCreate(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
var e Location
err := decoder.Decode(&e, r.PostForm)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid request payload")
return
}
// --- SUCCESS ---
// If e.Title has data, the following line works.
// --- FAIL ---
// If e.Title doesn’t have data (for whatever reason), it’s null, and crashes the app:
log.Println(*e.Title)
// Ultimately the variable would be sent off to a database.
// Below I’m removing other functions and such, just including my statement line.
// --- SUCCESS ---
// If e.Title has data, the following line works.
// --- FAIL ---
// If e.Title is null (e.g. no user input), this crashes the app.
statement := fmt.Sprintf("INSERT INTO locations(title) VALUES('%s')", *e.Title)
// In either case, the crash error is similar to this:
// panic serving [::1]:52459: runtime error: invalid memory address or nil pointer dereference
}
CONCERN 1: How can I make use of nullable variables (like e.Title), throughout the app, without throwing panic errors when the variable is null? Is the best practice to wrap it in a function that converts null to “” strings? How can such a function be applied transparently, so I don’t have to have something like “nullCheck(*e.Title)” on every instance of the variable?
CONCERN 2: In the case of my DB queries, I can’t be sending “” string values into the database in place of nulls. Up to now my queries are manually built. I suppose I need a function to generate the SQL queries automatically excluding columns and variables when the variables are null.
Am I on the right track? Any examples?
I haven’t understood all the threads/tutorials after hours of searching.