go – Trouble scanning data to exported structs-ThrowExceptions

Exception or error:

I’m working on my first Go application, and I’m trying to keep my files well organized, DRY, etc. I have a struct that represents the data I expect to receive from my SQL queries, defined in a closure environment that returns my request handlerFunc. Pared down version:

func (s *server) getComponents() http.HandlerFunc {

  type component struct {
        ID     int    `json:"_id,omitempty"`
        Name   string `json:"name"`
        // ... many more fields
  }

  return func(res http.ResponseWriter, req *http.Request) {

        rows, err := s.db.GetComponents()
        defer rows.Close()

        if err != nil {
            s.testQueryError(err, "etc, etc")
            return
        }

        var components []component

        for rows.Next() {
            var c component
            rows.Scan(&c)
            components = append(components, c)
        }

        data, _ := json.Marshal(components)

        res.Write(data)
    }
}

This implementation responds with the expected data. However, I expected that I may need this struct in other routes, and thought that it would be good practice to define this struct elsewhere and export it from a “models” directory/package. New attempt:

// app/models/models.go
package "models"
type Component struct {
  ID     int    `json:"_id,omitempty"`
  // ... 
}

// app/routes.go
import "app/models"

func (s *server) getComponents() http.HandlerFunc {

  return func(res http.ResponseWriter, req *http.Request) {

        rows, err := s.db.GetComponents()
        // ...

        var components []models.Component

        for rows.Next() {
            var c models.Component
            rows.Scan(&c)
            components = append(components, c)
        }

        data, _ := json.Marshal(components)

        res.Write(data)
    }
}

This version does not properly Scan, and Postman receives all empty fields. I’m new to strongly typed languages like Go, so could anybody point me in the right direction on where I am going wrong? The package is being properly exported/imported, so why should it work any differently?

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *