mercredi 18 janvier 2017

How to instantiate value of unknown type in Go?

I develop some server in golang. I try to create some wrapper-function, which can helps me in future.

What I have:

1) I had some DTO structs, for example:

type Request struct {
    Field1   string `json:"field1"`
    Field2   string `json:"field2"`
}

type Response struct {
    Field1   string `json:"field1"`
    Field2   string `json:"field2"`
    Field3   string `json:"field3"`
}

2) I had some functions, in controller layer, which (by conventions) receives 1 argument (pointer to struct) and returns 1 result (pointer to struct), for example:

func SomeHandler(request *Request) *Response{
    ...do something
    return &Response{"first","second","third"}
}

What I need:

I need to write wrapper function which receives as argument:

  1. pointer to 'controller' function
  2. http.ResponseWriter
  3. *http.Request

This wrapper function must:

  1. Determine type of argument of 'controller' function
  2. Determine type of result of 'controller' function
  3. Instantiate and fill argument value from Body of *http.Request (decode from json)
  4. Call controller Function with instantiated on previous step argument
  5. Write results of previous step into http.ResponseWriter (encoded as json)

Wrapper must work correct with any types of 'controller' functions - signatures of this functions is different (different argument type, different result type)

Can anybody help me with implementing of this wrapper?





Aucun commentaire:

Enregistrer un commentaire