#Need help with a web function - beginner

4 messages · Page 1 of 1 (latest)

winged gull
#
func (m *SnippetModel) Get(id int) (*models.Snippet, error) {
    stmt := `SELECT id, title, content, created, expires FROM snippets 
    WHERE expires > UTC_TIMESTAMP() AND id = ?`
    row := m.DB.QueryRow(stmt, id)

    s := &models.Snippet{}

    err := row.Scan(&s.ID, &s.Title, &s.Content, &s.Created, &s.Expires)
    if err == sql.ErrNoRows {
        return nil, models.ErrNoRecord
    } else if err != nil {
        return nil, err
    }

    return s, nil
}

my server is crashing and telling me that I'm pointing to a nul reference. the m == nil , i checked using a if statement , I don't know why it's nil though

woeful notch
#

if m is nil, the problem isn't in this function

#

the problem is in whatever is calling this function, whatever you define m

winged gull
# woeful notch the problem is in whatever is calling this function, whatever you define m

type SnippetModel struct {
    DB *sql.DB
}```

```go
func (app *application) showSnippets(w http.ResponseWriter, r *http.Request) {

    id, err := strconv.Atoi(r.URL.Query().Get("id"))

    if err != nil || id < 1 {
        app.notFound(w)
        return
    }

    // fmt.Fprintf(w, "Display a the snippet with id %d", id)

    s,err:=app.snippets.Get(id)
    if err!=models.ErrNoRecord{
        app.notFound(w)
    }else if err!=nil{
        app.serveError(w,err)
    }
    fmt.Fprintf(w, "%v", s) 

}