Handle dynamic role and function names

Asked

Viewed 47 times

1

I’m on my first Golang project, which consists of a small router for an MVC structure. Basically, what I expect him to do is take the request URL, separate it into pieces, and forward the execution flow to the package and function specified in these pieces, providing some kind of fallback when there is no correlation to these values in the application.

An alternative would be to map all Packages and functions into variables, then look for requests in the contents of those variables, but this is not a dynamic solution.

The alterative I have used in other languages is to deal with these names in a dynamic way in reference to the package/function, where the language somehow considers the value of the variable instead of considering its literal. Anything like: {packagename}. {functionName}() . The problem is I haven’t figured out any syntactic way to do this in Golang.

I appreciate the suggestions.

func ParseUrl(request *http.Request) {

    //out of this URL http://www.mydomain.com/controller/method/key=2&anotherKey=3

    var requestedFullURI = request.URL.RequestURI()      // returns '/controller/method?key=2key=2&anotherKey=3'
    controlFlowString, _ := url.Parse(requestedFullURI)       // returns '/controller/method'
    substrings := strings.Split(controlFlowString.Path, "/")       // returns ["","controller","method"]
    
    if len(substrings[1]) > 0 {

        // Here  we'll check if substrings[1] mathes an existing package(controller) name

        if len(substrings[2]) > 0 {
            // check if substrings[2] matches an existing function name(method) inside the requested package and run it, passing on the control flow
        }else{
            // there's no requested method, we'll just run some fallback
        }
    } else {
        err := errors.New("You have not determined a valid controller.")
        fmt.Println(err)
    }

}
  • If you create a type X struct{} and then func (x *X) Funcao(), you can use as x.Funcao(), assuming you define var x X.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.