package app

import (
	"common/log"
	"context"
	"errors"
	"net/http"
	_ "net/http/pprof"
	"sync"
)

// ModulePprof pprof模块
type ModulePprof struct {
	wg     *sync.WaitGroup
	server *http.Server
}

func (m *ModulePprof) init() error {
	m.wg = &sync.WaitGroup{}
	return nil
}

func (m *ModulePprof) start() error {
	m.wg.Add(1)
	go func() {
		defer m.wg.Done()
		m.server = &http.Server{
			Addr: "localhost:6060",
		}
		if err := m.server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Errorf("pprof server failed: %v", err.Error())
		}
		log.Infof("pprof server stop.")
	}()
	return nil
}

func (m *ModulePprof) stop() error {
	if err := m.server.Shutdown(context.Background()); err != nil {
		log.Errorf("stop pprof server failed: %v", err)
	}
	m.wg.Wait()
	return nil
}
