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