GO 中间件方式执行额外任务

package main

import (
	"database/sql"
	"fmt"
	"mylog"
	"time"
)

type Middleware struct{}

/*如遇错误,执行额外任务*/
func (m *Middleware) Println(v interface{}) {
	if err, ok := v.(error); ok {
		mylog.Println("执行额外任务:", err)
	}
	mylog.Println("正常执行原本任务:", v)
}

var dblink *sql.DB /*自行补充初始化过程*/

/*如遇错误,执行额外任务*/
func (m *Middleware) Println_sendln(v ...interface{}) {

	for _, arg := range v {
		if err, ok := arg.(error); ok {
			mylog.Println("错误信息:", err)
			err_msg := `警告消息:` + err.Error() //错误信息里可能有单引号
			dingdingmsg := `exec dingding_add_msg ?,0,'xxk'`
			//	mylog.Println("sql:", dingdingmsg)
			dblink.Exec(dingdingmsg, err_msg)
		}
	}

	mylog.Println(v...)
}

func main() {

	if err := DBinit_sqlserver2(); err != nil {
		mylog.Println(err)
		fmt.Println(err)
		time.Sleep(5 * time.Minute)
		return
	} else {
		fmt.Println(`链接sqlserver2成功`)
	}

	mv := &Middleware{}

	mv.Println(11)
	mv.Println(22)
	mv.Println(fmt.Errorf("自定义错误"))
	mv.Println_sendln(fmt.Errorf("测试自定义错误"), `121`)
}

 

  

写个函数调用似乎没什么不同

 

var logFile_handel_wx, _ = os.OpenFile(`./log/`+time.Now().Format("2006-01-02")+`--wx_api.log`, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)

var mylog_wx = log.New(logFile_handel_wx, "", log.Lmicroseconds|log.Ldate)

func ffmyprint(Logger *log.Logger, v ...interface{}) {
	for _, arg := range v {
		if err, ok := arg.(error); ok {
			Logger.Println("ffmyprint 错误信息:", err)
			 
		}
	}

	Logger.Println(v...)
}
    ffmyprint(mylog_wx, fmt.Errorf("测试自定义错误"), `121`)

 

  

 

posted @ 2024-05-14 10:06  wsh3166Sir  阅读(6)  评论(0编辑  收藏  举报