go - Return void function with result of another void function? -


i'm trying come compact way of handling problems may arise in http requests rest api.

there many conditions need test for, , many potential error responses failure of of these conditions.

i've gotten handling flow down looks similar following:

// error method on struct, it's relevant demonstration purposes. func error(w http.responsewriter, status int, message string) {   // lots of stuff omitted   w.writeheader(status)   w.writejson(r) }  func handlesomething(w http.responsewriter, r *http.request) {   if somecondition != true {     error(w, 500, "some error occurred!")     return   }   if someothercondition != true {     error(w, 500, "some other error occurred!")     return   }   if yetanothercondition != true {     error(w, 500, "yet error occurred!")     return   }   if andfinallyonelastcondition != true {     error(w, 500, "one final error occurred!")     return   }   // good! send real data.   w.writejson(someobject) } 

since there 5-10 conditions need test for, , other errors can arise during other operations, nice able compact following:

func handlesomething(w http.responsewriter, r *http.request) {   if somecondition != true {     return error(w, 500, "some error occurred!")   }   if someothercondition != true {     return error(w, 500, "some other error occurred!")   }   if yetanothercondition != true {     return error(w, 500, "yet error occurred!")   }   if andfinallyonelastcondition != true {     return error(w, 500, "one final error occurred!")   }   // good! send real data.   w.writejson(someobject) } 

however, go compiler doesn't this.

it complains both i'm trying use result of error() value, , i'm trying return many arguments. exact error messages are:

foo.go:41: bar.response.error(400, "invalidrequest", "error decoding request") used value foo.go:41: many arguments return 

but both error() , handlesomething() have same return signature (e.g. both return nothing), shouldn't work?

it's important each if statement contains return, because function should exited immediately. if error() somehow stop execution of calling function, work me. sort of testing.failnow(), believe relies on goroutines.

as aside: realize these aren't "void" functions, couldn't think of more appropriate name. there proper name functions return nothing in go?

c++ allows this. handy templates.

but see go not. not sure of exact steps, seems ask added go, perhaps make in 1.7.

as solution right now, perhaps return unused error. return nil error function.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -