How do I pass arguments to my handler

后端 未结 1 1368
温柔的废话
温柔的废话 2021-01-31 07:40

I am trying to pass my database object along to my handlers, instead of having a global object. But I don\'t know if this is possible, I\'m using Gorilla Mux package, and I can

1条回答
  •  情话喂你
    2021-01-31 08:24

    Welcome to Go.

    It is acceptable to have global variables and specially database objects.

    However, there are few ways to workaround that if you prefer not to, for example you can create a struct and define your showHandler on it.

    type Users struct {
        db *gorm.DB
    }
    
    func (users *Users) showHandler(w http.ResponseWriter, r *http.Request) {
        //now you can use users.db
    }
    func (users *Users) addHandler(w http.ResponseWriter, r *http.Request) {
        //now you can use users.db
    }
    
    // setup
    users := &Users{db: createDB()}
    router.HandleFunc("/users/{id}", users.showHandler).Methods("GET")
    router.HandleFunc("/users/new", users.addHandler)
    //etc
    

    Another approach is creating a wrapper function:

    db := createDB()
    router.HandleFunc("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
        showUserHandler(w, r, db)
    }).Method("GET")
    

    0 讨论(0)
提交回复
热议问题