Right now I have this:
type AppError struct{
Status int
Message string
}
func (h NearbyHandler) makeUpdate(v NearbyInjection) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
item, ok := v.Nearby[params["id"]]
if !ok {
return AppError{
500, "Missing item in map.",
}
}
}
}
the problem is that if I do this:
func (h NearbyHandler) makeUpdate(v NearbyInjection) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) AppError { // <<< return AppError
}
}
that won't compile b/c http.HandlerFunc doesn't return a function which returns AppError.
Another question I have, how can I avoid explicitly returning nil
if if I use AppError as the return value?
Note that I get this error:
cannot use func literal (type func(http.ResponseWriter, *http.Request) AppError) as type http.HandlerFunc in return argument
So instead of returning the status for the request the designers of go give you the ResponseWriter. This is your main interaction with the client. For example to set a status code, do WriteHeader(500)
.
that won't compile b/c http.HandlerFunc doesn't return a function which returns AppError.
Why you don't handle error directly in makeUpdate method?
how can I avoid explicitly returning nil if if I use AppError as the return value?
Cannot use 'nil' as type AppError in return argument, you can use the initial value, like this:
func test() AppError {
ret := AppError{
200, "OK",
}
condition := true // some condition
if !condition {
ret.Status = 500
ret.Message = "internal error"
}
return ret
}