github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/pkg/admin/server.go (about)

     1  package admin
     2  
     3  import (
     4  	"net/http"
     5  	"os"
     6  
     7  	"github.com/pyroscope-io/pyroscope/pkg/api"
     8  	"github.com/pyroscope-io/pyroscope/pkg/server/httputils"
     9  
    10  	"github.com/gorilla/handlers"
    11  	"github.com/gorilla/mux"
    12  	"github.com/sirupsen/logrus"
    13  )
    14  
    15  type Server struct {
    16  	log     *logrus.Logger
    17  	ctrl    *Controller
    18  	Handler http.Handler
    19  
    20  	HTTPServer
    21  }
    22  
    23  type HTTPServer interface {
    24  	Start(http.Handler) error
    25  	Stop() error
    26  }
    27  
    28  // NewServer creates an AdminServer and returns an error
    29  // Is also does basic verifications:
    30  // - Checks if the SocketAddress is non empty
    31  func NewServer(logger *logrus.Logger, ctrl *Controller, httpServer HTTPServer) (*Server, error) {
    32  	as := &Server{
    33  		log:  logger,
    34  		ctrl: ctrl,
    35  	}
    36  	as.HTTPServer = httpServer
    37  
    38  	// use gorilla mux
    39  	r := mux.NewRouter()
    40  
    41  	as.Handler = r
    42  
    43  	httpUtils := httputils.NewDefaultHelper(logger)
    44  	// Routes
    45  
    46  	applicationsHandler := api.NewApplicationsHandler(ctrl.appService, httpUtils)
    47  	r.HandleFunc("/v1/apps", applicationsHandler.GetApps).Methods("GET")
    48  	r.HandleFunc("/v1/apps", applicationsHandler.DeleteApp).Methods("DELETE")
    49  
    50  	r.HandleFunc("/v1/users/{username}", ctrl.UpdateUserHandler).Methods("PATCH")
    51  	r.HandleFunc("/v1/storage/cleanup", ctrl.StorageCleanupHandler).Methods("PUT")
    52  
    53  	// Global middlewares
    54  	r.Use(logginMiddleware)
    55  
    56  	return as, nil
    57  }
    58  
    59  func (as *Server) Start() error {
    60  	return as.HTTPServer.Start(as.Handler)
    61  }
    62  
    63  func (as *Server) Stop() error {
    64  	return as.HTTPServer.Stop()
    65  }
    66  
    67  func logginMiddleware(next http.Handler) http.Handler {
    68  	// log to Stdout using Apache Common Log Format
    69  	// TODO maybe use JSON?
    70  	return handlers.LoggingHandler(os.Stdout, next)
    71  }