Some functions need to add logs, record time, and deal with panic before and after execution, all of which are repetitive things.
So get a template-type thing, meet this kind of demand, directly to the relevant functions and parameters, throw to the run function to go without the tube, save time.
First, the previous invocation example:
The function executes the template//author:xiong Chuan liang//date:2015-3-19package mainimport ("FMT" "Log" "OS" "Utils") func main () {log. Setoutput (OS. Stdout) W: = Utils. Newworker () W.run ("myprintf ()", myprintf, "AA", "BB")}func myprintf (args ... interface{}) (int, error) {FMT. Println ("myprintf () begin.") For _, arg: = Range args {fmt. Println ("args:", Arg)}fmt. Println ("myprintf () end.") Panic ("Attempt to throw panic error") return 0, nil}/* run result: 2015/03/19 13:49:30 [worker. Run ()] Function: myprintf () myprintf () begin.args:aaargs:bbmyPrintf () End.2015/03/19 13:49:30 [worker. Run ()] panic:myprintf () tries to throw panic error 2015/03/19 13:49:30 [worker. Run ()] Function: myprintf () Time: 0.004000 sec */
It is also convenient to call, passing in functions and accompanying parameters.
The implementation is also simple:
The function executes the template//author:xiong Chuan liang//date:2015-3-19package utilsimport ("FMT" "Log" "Time") type Workerfunc func (... interface{}) (int, error) type worker struct {}func newworker () *worker {return &worker{}}func (w *worker) Run (name str ING, Workerfunc workerfunc, args ... interface{}) (int, error) {now: = time. Now () log. Println ("[Worker. Run ()] Function: ", name" defer func () {if r: = Recover (); R! = Nil {log. Println ("[Worker. Run ()] panic:\n ", name," \ n ", FMT. Sprint (R)) w.elasped (name, now, time. Now ())}} () ret, err: = Workerfunc (args ...) w.elasped (name, now, time.) Now ()) return RET, Err}func (w *worker) elasped (name string, BeginTime, EndTime time. Time) {log. Printf ("[Worker. Run ()] function:%s Time:%f sec \ n ", Name, Endtime.sub (beginTime). Seconds ())}
Not a lot of things, I also deal with the Func (... interface{}) (int, error) Such functions, the other is out of control.
blog:http://blog.csdn.net/xcl168
MAIL: [Email protected]
Golang function Execution Template (log, time-consuming, panic)