github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/service/debug/profile/http/http.go (about)

     1  // Licensed under the Apache License, Version 2.0 (the "License");
     2  // you may not use this file except in compliance with the License.
     3  // You may obtain a copy of the License at
     4  //
     5  //     https://www.apache.org/licenses/LICENSE-2.0
     6  //
     7  // Unless required by applicable law or agreed to in writing, software
     8  // distributed under the License is distributed on an "AS IS" BASIS,
     9  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    10  // See the License for the specific language governing permissions and
    11  // limitations under the License.
    12  //
    13  // Original source: github.com/micro/go-micro/v3/debug/profile/http/http.go
    14  
    15  // Package http enables the http profiler
    16  package http
    17  
    18  import (
    19  	"context"
    20  	"net/http"
    21  	"net/http/pprof"
    22  	"sync"
    23  
    24  	"github.com/tickoalcantara12/micro/v3/service/debug/profile"
    25  )
    26  
    27  type httpProfile struct {
    28  	sync.Mutex
    29  	running bool
    30  	server  *http.Server
    31  }
    32  
    33  var (
    34  	DefaultAddress = ":6060"
    35  )
    36  
    37  // Start the profiler
    38  func (h *httpProfile) Start() error {
    39  	h.Lock()
    40  	defer h.Unlock()
    41  
    42  	if h.running {
    43  		return nil
    44  	}
    45  
    46  	go func() {
    47  		if err := h.server.ListenAndServe(); err != nil {
    48  			h.Lock()
    49  			h.running = false
    50  			h.Unlock()
    51  		}
    52  	}()
    53  
    54  	h.running = true
    55  
    56  	return nil
    57  }
    58  
    59  // Stop the profiler
    60  func (h *httpProfile) Stop() error {
    61  	h.Lock()
    62  	defer h.Unlock()
    63  
    64  	if !h.running {
    65  		return nil
    66  	}
    67  
    68  	h.running = false
    69  
    70  	return h.server.Shutdown(context.TODO())
    71  }
    72  
    73  func (h *httpProfile) String() string {
    74  	return "http"
    75  }
    76  
    77  func NewProfile(opts ...profile.Option) profile.Profile {
    78  	mux := http.NewServeMux()
    79  
    80  	mux.HandleFunc("/debug/pprof/", pprof.Index)
    81  	mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
    82  	mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
    83  	mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
    84  	mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
    85  
    86  	return &httpProfile{
    87  		server: &http.Server{
    88  			Addr:    DefaultAddress,
    89  			Handler: mux,
    90  		},
    91  	}
    92  }