package main

import (
	MC "app.yhyue.com/moapp/jybase/common"
	"app.yhyue.com/moapp/jybase/endless"
	logrusx "app.yhyue.com/moapp/jylogx/logx"
	"bp.jydev.jianyu360.cn/BaseService/gateway/core/node"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	IC "jyBXCore/api/init"
	"jyBXCore/api/internal/handler"
	"jyBXCore/api/internal/svc"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"github.com/zeromicro/go-zero/rest"
)

func main() {
	//注册代理服务
	closeNotify, err := node.NewNode(IC.C.Gateway.Etcd...).Register(IC.C.Gateway.ServerCode, MC.InterfaceToStr(IC.C.Port))
	if err != nil {
		panic(err)
	}
	//
	go func() {
		err := endless.ListenAndServe(":"+MC.InterfaceToStr(IC.C.Webrpcport), nil, func() {})
		if err != nil {
			log.Println("ListenAndServe: ", err)
		}
	}()
	ctx := svc.NewServiceContext(IC.C)
	server := rest.MustNewServer(IC.C.RestConf)
	defer server.Stop()
	//全局中间件
	server.Use(func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			defer func() {
				MC.AddMgoLogs(IC.MgoLog, r, IC.C.MgoLogsName, IC.ExcludeUrl, IC.C.MgoLogsCount)
			}()
			next.ServeHTTP(w, r)
		}
	})
	//日志记录
	logx.SetWriter(logrusx.NewLogrusWriter())

	handler.RegisterHandlers(server, ctx)
	fmt.Printf("Starting server at %s:%d...\n", IC.C.Host, IC.C.Port)
	server.Start()

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	closeNotify()
}
