R
R
Roman Rakzin2015-07-14 20:26:46
go
Roman Rakzin, 2015-07-14 20:26:46

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)

etc.
And you need to perform certain actions for all controllers (authorization check, etc.). Is it possible to write a function with a check once, and then attach it to all the necessary functions?
So far, I only see a cumbersome option - this is the launch of a check function in all functions. Is there a constructor or inheritance option?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman Rakzin, 2015-07-15
@TwoRS

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, "это обрабатывается в обёртке)) ")
    }

....

A
Artem, 2015-07-14
@artem_kovardin

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 ".

S
SilentFl, 2015-07-15
@SilentFl

Discover middleware like interpose . Here is an example with authorization, everything is clean and your functions are not affected

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question