I have a model file in which there is a struct method. That method I want to use in my controller. But it is saying "GetBookings not declared by package models". I am very new to Golang, may be it is a silly question still I’m stuck with it. If someone can rectify my code or may be give a another option how to use struct methods in another file, would be appreciated. Thanks in advance.
controller
package controllers
import (
"encoding/json"
"net/http"
"github.com/Coddyy/beautyfly/pkg/models"
)
func GetBookings(w http.ResponseWriter, r *http.Request) {
bookings, err := models.GetBookings()
res, _ := json.Marshal(bookings)
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(res)
}
model
package models
import (
"database/sql"
"github.com/Coddyy/beautyfly/pkg/entities"
)
type BookingModel struct {
Db *sql.DB
}
func init() {
}
func (bookingModel *BookingModel) GetBookings() ([]entities.Booking, error) {
rows, err := bookingModel.Db.Query("SELECT * FROM bookings")
if err != nil {
return nil, err
} else {
bookings := []entities.Booking{}
for rows.Next() {
var id int64
var customer_ids string
var date string
var time string
var service_ids string
var comments string
err2 := rows.Scan(&id, &customer_ids, &date, &time, &service_ids, &comments)
if err2 != nil {
return nil, err2
} else {
booking := entities.Booking{id, customer_ids, date, time, service_ids,
comments}
bookings = append(bookings, booking)
}
}
return bookings, nil
}
}
>Solution :
In order to call GetBookings() method of BookingModel you need an instance of BookingModel struct. Then you can call any method of BookingModel on that instance:
func GetBookings(w http.ResponseWriter, r *http.Request) {
var bookingModel = models.BookingModel{}
bookings, err := bookingModel.GetBookings()
// always do error checking
if err != nil {
...
}
res, err := json.Marshal(bookings)
// always do error checking
if err != nil {
...
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(res)
}