I am new to golang and trying to make API server using gin + gorm.
I tried to build the code below but I am getting type *gorm.DB has no field or method GetUsers
error.
This is a very simple API server and only I want to do is get all users from users
table.
package models
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
var db *gorm.DB
func init() {
var err error
db, err = gorm.Open("postgres", "host=localhost dbname=test user=postgres password=test sslmode=disable")
if err != nil {
return err
}
}
type User struct {
ID int `json:"id"`
Username string `json:"name"`
}
func NewUser(id int, name string) User {
return User{
ID: id,
Username: name,
}
}
// UserRepository
type UserRepository struct {
}
func NewUserRepository() UserRepository {
return UserRepository{}
}
func (m UserRepository) GetUsers() []*User {
var users []*User
has, _ := db.GetUsers(&users)
if has {
return users
}
return nil
}
I implemented GetUsers()
in controllers/user.go
and I also created users
table.
I have no idea why it says no field or method GetUsers
.Someone give me an advice to solve this.
package controllers
import (
"api-server/models"
)
type User struct {
}
func NewUser() User {
return User{}
}
func (c User) GetUsers() interface{} {
repo := models.NewUserRepository()
user := repo.GetUsers()
return user
}