From global vars to

Hello.

I’m trying to cut off all global vars in project. I found this example http://elithrar.github.io/article/custom-handlers-avoiding-globals/. It works when the “IndexHandler” is in the main file but it doesn’t work in another one (undefined: AppContext).

package main

import (	
    "fmt"
    "log"
    "net/http"

    "html/template"

    "github.com/gorilla/sessions"
    "github.com/zenazn/goji/graceful"
    "github.com/zenazn/goji/web"

	"github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"

	"server/routes"
)

const (
	DB_DATABASE = "go"
	DB_USER = "root"
	DB_PASSWORD = "123321wsx"
)

type AppContext struct {
    DB        *gorm.DB
    Store     *sessions.CookieStore
}

type AppHandler struct {
    *AppContext
    H func(*AppContext, http.ResponseWriter, *http.Request) (int, error)
}


func (ah AppHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    status, err := ah.H(ah.AppContext, w, r)
    if err != nil {
        log.Printf("HTTP %d: %q", status, err)
        switch status {
        case http.StatusNotFound:
            http.NotFound(w, r)
        case http.StatusInternalServerError:
            http.Error(w, http.StatusText(status), status)
        default:
            http.Error(w, http.StatusText(status), status)
        }
    }
}

func main() {
	db, err := gorm.Open("mysql", DB_USER + ":" + DB_PASSWORD + "@/" + DB_DATABASE + "?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
    	panic(err.Error())
	}
	defer db.Close()
    context := &AppContext{DB: db, Store: nil} 

    r := web.New()
    r.Get("/", AppHandler{context, routes.IndexHandler})
    graceful.ListenAndServe(":3000", r)
}

best regards

If you’re using go run, don’t. Or at least give it all files on the command line. If you’re doing something else, show us what you’re doing and what happens. :wink:

1 Like
package routes

import ( 
	"fmt"
    "net/http"
    _ "github.com/jinzhu/gorm/dialects/mysql"	
    "server/models"
)

func IndexHandler (a *AppContext, w http.ResponseWriter, r *http.Request) { //error here
	DBPosts := []models.DBPostModel{}
	a.DB.Where("published = ?", 1).Find(&DBPosts)

	posts := []models.DBPostModel{}
	for _, post := range DBPosts {
		posts = append(posts, post)
	}

	model := models.PostListModel{}
	model.IsAuthorized = true
	model.Posts = posts 

	fmt.Println(posts)
}

#error
“C:\gopath\src\server>go build main.go
server/routes
routes\home.go:10: undefined: AppContext”

Don’t give go build a file name.

the result is the same

You’re doing something weird or unusual with your file layouts. Read and following this article, and things should clarify: https://golang.org/doc/code.html

1 Like

you must import the package from where AppContext is coming.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.