So I have a global instance of the DB throughout my project. Here’s how I set that up.
type API struct {
db *gorm.DB
}
I created a package-wide variable called “api” to access within the project.
var api = API{
db: NewDB()
}
My NewDB function looks like this:
func NewDB() *gorm.DB {
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
panic(err)
}
return db
}
Here’s my Users model. Note that I did not extend gorm.Model in this case.
type User struct {
ID uuid.UUID `json:"id" gorm:"primary_key"`
Email string `json:"email" gorm:"not null;unique"`
Password string `json:"password"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt time.Time `json:"deleted_at"`
}
I have included a BeforeEach function atop the User model to fulfill a UUID because I prefer it over autoincrement. The ID works great, when I go inside the sqlite file and run a select * from users
query I get returned the id, the email, password, etc.
The issue I’m having is running this code:
func UsersIndex(w http.ResponseWriter, r *http.Request) {
var users Users
api.db.Find(&users)
data, _ := json.Marshal(&users)
fmt.Fprint(w, string(data))
}
It’s not the error marshalling the JSON, I’ve tried including that, and still nothing. My issue is that no matter what the raw query from SQLite says, I always get a blank list of Users. What’s weird is that it was working when my User model extended gorm.Model, however after I changed it that’s when it stopped working.
Thanks!