During the development of Serve I have learned the http handling of
Go. It is very strange for a Java developer but in my opinion it
suits the http protocol far more better than Java.
In Java you have objects but the methods aren't allowed to store
anything in the object during two http calls. In Go you have
handlers but the most common handler takes a function with this
signature:
func(http.ResponseWriter, *http.Request)
Here it is much clear that you shouldn't save variables outside the
function. You ask what to do when you need to get additional info
inside, like a list of strings you've loaded on start and that
should be used to handle the request. See this example:
func CreateDownloadFileListFunction(list []string)
(func(http.ResponseWriter, *http.Request), error) {
jsonList, err := json.Marshal(list)
if err != nil {
return nil, err
}
return func(w http.ResponseWriter, r
*http.Request) {
fmt.Fprintf(w, "%s",
jsonList)
}, nil
}
This is a function that creates a http handle function. Yes you can
return functions in Go and these functions can use variables given
to the creator function. The function here just returns some json
data derived from the string list but there is more to it.
Imagine that function would get another function of the type used to
handle http requests. Now you can return a function that checks user
access and when the check was positive it will call the given
function. That way you can separate the technical security aspect
from the business logic. All without the Annotations and byte code
manipulation you would need in Java.
Another remarkable point is the registration for handling an URL:
mux := http.NewServeMux()
mux.HandleFunc("/downloadfileload",
downloadFileLoadFunction)
log.Fatal(http.ListenAndServe(":8181",
mux))
Here you have to explicitly write the URL for which a function is
responsible. No annotation and convention, just plain code. That
doesn't sound cool but when done correct it is fare more
understandable than those auto magic used by others. I had to learn
this lesson when I switched from XML based ADF to code based
JGoodies for Swing GUI binding.