go - How to pass type into an http handler -
i'm attempting separate http go code "controllers" creating new package them, can't figure out how pass db type handler. want able pass in db type create in main.go index handler in index.go. if wrong way solve this, let me know better way (i'm learning go , keep simple now). code far:
main.go:
package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" "github.com/gorilla/mux" "log" "mvc3/app/c" "net/http" ) var db *sql.db func main() { fmt.println("starting up!") var err error db, err = sql.open("mysql", "root@/dev?charset=utf8") if err != nil { log.fatalf("error on initializing database connection: %s", err.error()) } db.setmaxidleconns(100) err = db.ping() if err != nil { log.fatalf("error on opening database connection: %s", err.error()) } r := mux.newrouter() r.handlefunc("/", c.index) http.handle("/", r) http.listenandserve(":8080", nil) }
/app/c/index.go:
package c import ( "fmt" "net/http" ) func index(w http.responsewriter, r *http.request) { fmt.fprintf(w, "hello world!") }
thanks!
use closure.
in app/c change index to:
func index(db *sql.db) func(w http.responsewriter, r *http.request) { return func(w http.responsewriter, r *http.request) { // stuff db here fmt.fprintf(w, "hello world!") } }
then in main function use so: r.handlefunc("/", c.index(db))
the index function returns anonymous function fits the handlefunc type , closes on value of db passed in giving handler access variable.
Comments
Post a Comment