Answer the question
In order to leave comments, you need to log in
Is it possible to write a constructor function in golang or inherit from another function?
Good afternoon.
I write routing
import "github.com/gorilla/mux"
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", Index)
router.HandleFunc("/api/:controller/:action", ApiHandler)
Answer the question
In order to leave comments, you need to log in
Among the entire Internet, I have not found an elementary example. Thanks for the tips on which direction to go.
Here is the solution
type logWrapper struct {
http.Handler
}
func (wr logWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s\n", r.Method, r.URL, time.Now())
wr.Handler.ServeHTTP(w, r)
}
func main() {
router := mux.NewRouter()
s := http.StripPrefix("/static/", http.FileServer(http.Dir("./files/")))
router.HandleFunc("/", Index)
router.HandleFunc("/login", LogIn)
router.HandleFunc("/logout", LogOut)
FileHandler := http.HandlerFunc(File)
router.Handle("/file.html", logWrapper{FileHandler})
router.PathPrefix("/static/").Handler(s)
http.Handle("/", router)
http.ListenAndServe(":5000", nil)
}
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello")
}
func File(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "это обрабатывается в обёртке)) ")
}
All handlers in Go implement the http.Handler interface and you can write wrappers for them. Here is an article with details " Handlers and getting rid of global variables ".
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question