I am starting building a api in go(golang), but I have few questions...
So in my main function or init function(because I might use appengine) I was thinking in calling a function which will define all my routes using gorilla mux. Each pice of my application(post, comments etc...) will have its one package with its structures/methods/functions.
Questions:
Because I was thinking in defining the routes in one function, do I need to import in this file all my packages, to send the requests to the right handlers?
What about helper function, for example I would like to set content type
of the response to be application/json
for all the handlers where this is necessary, how I will be able to do that?
I'm not looking for frameworks, just some pointer about how can I overcome those questions in golang way.
If you define all of the routes in a single function, then the file containing this function will need to import the packages that implement the handlers. The only way to refer to a type or function in another package is to import the package.
Here's a helper for setting the content type and encoding a value to JSON:
func JSONHandler(f func(w http.ResponseWriter, r *http.Request) interface{}) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
v := f(w, r)
if v != nil {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(v); err != nil {
log.Println(err)
}
}
})
}
The argument to this function is a function that returns a value to encode to the response as JSON. For example, this function returns the client's user agent as JSON.
func UserAgentHandler(w http.ResponseWriter, r *http.Request) interface{} {
return struct { UserAgent string }{ req.Header.Get("User-Agent") }
}
Use the following code to register this handler with the Gorilla mux r
:
r.Handle("/user-agent", JSONHandler(UserAgentHandler))
There are many ways to improve JSONHandler.