Documentation ¶
Overview ¶
Package app provides functions to work with main server - metric collector
Index ¶
- Constants
- Variables
- func GzipMiddleware(h http.Handler) http.Handler
- func WithLogging(h http.Handler) http.Handler
- type IMetric
- type Server
- func (srv *Server) AddMetric(ctx context.Context, metricType string, metricName string, metricValue string) errordeprecated
- func (srv *Server) AddMetricNew(ctx context.Context, m metrics.Metric) error
- func (srv *Server) AddMetricsBatch(ctx context.Context, m []metrics.Metric) error
- func (srv *Server) AllMetricsHandle(w http.ResponseWriter, r *http.Request)
- func (srv *Server) AsyncSaving(ctx context.Context)
- func (srv *Server) CheckHashMiddleware(h http.Handler) http.Handler
- func (srv *Server) DecryptMiddleware(h http.Handler) http.Handler
- func (srv *Server) GetAllMetricsNew(ctx context.Context) ([]*metrics.Metric, error)
- func (srv *Server) GetMetricValue(ctx context.Context, metricType string, metricName string) (any, error)
- func (srv *Server) GetRequestedValues(ctx context.Context, m []metrics.Metric) ([]metrics.Metric, error)
- func (srv *Server) GetValueHandle(w http.ResponseWriter, r *http.Request)
- func (srv *Server) GetValueJSONHandle(w http.ResponseWriter, r *http.Request)
- func (srv *Server) Ping(ctx context.Context) error
- func (srv *Server) PingHandle(w http.ResponseWriter, r *http.Request)
- func (srv *Server) PushMetrics(ctx context.Context, in *pb.PushMetricsRequest) (*pb.PushMetricsResponse, error)
- func (srv *Server) ReadFromFile() ([]metrics.Metric, error)
- func (srv *Server) RestoreValues(ctx context.Context)
- func (srv *Server) SaveToFile(ctx context.Context) error
- func (srv *Server) StartServer(ctx context.Context, srvFlags *config.ServerFlags)
- func (srv *Server) StopAsyncSaving()
- func (srv *Server) StopServer(ctx context.Context)
- func (srv *Server) UpdateBatchJSONHandle(w http.ResponseWriter, r *http.Request)
- func (srv *Server) UpdateHandle(w http.ResponseWriter, r *http.Request)
- func (srv *Server) UpdateJSONHandle(w http.ResponseWriter, r *http.Request)
- func (srv *Server) ValidateIP(h http.Handler) http.Handler
Examples ¶
Constants ¶
const ( DatabaseStorageType = "db" MemStorageType = "memory" )
Variables ¶
var ContentTypesForCompress = "application/json; text/html"
type needed compress
var Sugar zap.SugaredLogger
Main logger
Functions ¶
Types ¶
type IMetric ¶
type IMetric interface { GetName() string GetType() string GetValue() any GetTypeForQuery() string }
IMetric provides functions to operate with metrics stored in DB
type Server ¶
type Server struct { // Address of web server, where app woul be deployed // Format - Host[:Port] Address string // Interval in seconds for backup storage on disk StoreInterval int // Path to save storage with interval StoreInterval FileStoragePath string // True if server would restore metrics from backup file Restore bool // String connection to postgres DB // Format - "user=<user> password=<pass> host=<host> port=<port> dbname=<db> sslmode=<true/false>" DBConnection string // "db" or "memory" StorageType string // Key for decrypt and encrypt body of requests HashKey string // True if server would validate hash of all incoming requests CheckHash bool // True if server accepts encrypted messages from agent UseEncryption bool // Path to private key RSA PrivateKeyPath string // Trusted subnet to check clients ip addresses TrustedSubnet string // http server HTTPServer *http.Server // Path to file where mem stats will be saved MemProfile string // Exchange mode ExchangeMode string // implement GRPC server pb.UnimplementedMetricServerServer // contains filtered or unexported fields }
func NewServer ¶
func NewServer(settings *config.ServerFlags) (*Server, error)
NewServer creates app instance
func (*Server) AddMetricNew ¶
AddMetricNew adds new metric if it doesn't exist, or update existing metric with name metricName
func (*Server) AddMetricsBatch ¶
AddMetricsBatch adds array of new metrics. Behavior is the same as in AddMetricNew
func (*Server) AllMetricsHandle ¶
func (srv *Server) AllMetricsHandle(w http.ResponseWriter, r *http.Request)
AllMetricsHandle godoc @Tags getvalue @Summary Get all metrics @Description Get all metrics with current values @ID getvalue @Accept plain @Produce json @Success 200 {string} string "OK" @Failure 405 {string} string "Invalid request type" @Failure 500 {string} string "Internal error" @Router /value/{type}/{name} [get]
Example ¶
client := &http.Client{} address := "localhost:8080" url := "http://" + address + "/" bodyBuffer := new(bytes.Buffer) request, err := http.NewRequest(http.MethodGet, url, bodyBuffer) if err != nil { fmt.Printf("Error request: %v", err.Error()) return } response, err := client.Do(request) if err != nil { fmt.Printf("Error response: %v", err.Error()) return } defer response.Body.Close() dataResponse, err := io.ReadAll(response.Body) if err != nil { fmt.Printf("Error reading response body: %v", err.Error()) return } var allmetrics []metrics.Metric reader := io.NopCloser(bytes.NewReader(dataResponse)) if err := json.NewDecoder(reader).Decode(&allmetrics); err != nil { fmt.Print("Error to parse response body") return } if response.StatusCode != http.StatusOK { fmt.Printf("Error response") return } fmt.Printf("all metrics: %v", allmetrics)
Output:
func (*Server) AsyncSaving ¶
AsyncSaving backups database to file
func (*Server) CheckHashMiddleware ¶
func (*Server) DecryptMiddleware ¶
func (*Server) GetAllMetricsNew ¶
GetAllMetricsNew returns all existed metrics with current values
func (*Server) GetMetricValue ¶
func (srv *Server) GetMetricValue(ctx context.Context, metricType string, metricName string) (any, error)
GetMetricValue returns current value of metric
func (*Server) GetRequestedValues ¶
func (srv *Server) GetRequestedValues(ctx context.Context, m []metrics.Metric) ([]metrics.Metric, error)
GetRequestedValues returns current values of requested metrics. return only already existed metrics
func (*Server) GetValueHandle ¶
func (srv *Server) GetValueHandle(w http.ResponseWriter, r *http.Request)
GetValueHandle godoc @Tags getvalue @Summary Get value of existed metric @Description Get value of existed metric @ID getvalue @Accept plain @Produce plain @Param type path string true "Metric type" @Param name path string true "Metric name" @Success 200 {string} string "OK" @Failure 400 {string} string "Invalid type" @Failure 404 {string} string "Missing name of metric" @Failure 405 {string} string "Invalid request type" @Failure 500 {string} string "Internal error" @Router /value/{type}/{name} [get]
func (*Server) GetValueJSONHandle ¶
func (srv *Server) GetValueJSONHandle(w http.ResponseWriter, r *http.Request)
GetValueJSONHandle godoc @Tags getvalue @Summary Get metric value @Description Get metric value @ID getvalueJSON @Accept json @Produce json @Param metric body metrics.Metric true "metric" @Success 200 {string} string "OK" @Failure 400 {string} string "Invalid type or value" @Failure 404 {string} string "Missing name of metric" @Failure 405 {string} string "Invalid request type" @Failure 500 {string} string "Internal error" @Router /value/ [get]
func (*Server) PingHandle ¶
func (srv *Server) PingHandle(w http.ResponseWriter, r *http.Request)
PingHandle godoc @Tags checks @Summary Checking db connection @Description Checking db connection @ID checksPing @Accept plain @Produce plain @Success 200 {string} string "OK" @Failure 500 {string} string "Внутренняя ошибка" @Router /ping [get]
Example ¶
client := &http.Client{} address := "localhost:8080" url := "http://" + address + "/ping" bodyBuffer := new(bytes.Buffer) request, err := http.NewRequest(http.MethodGet, url, bodyBuffer) if err != nil { fmt.Printf("Error request: %v", err.Error()) return } response, err := client.Do(request) if err != nil { fmt.Printf("Error response: %v", err.Error()) return } defer response.Body.Close() if response.StatusCode != http.StatusOK { fmt.Printf("Error response") return }
Output:
func (*Server) PushMetrics ¶
func (srv *Server) PushMetrics(ctx context.Context, in *pb.PushMetricsRequest) (*pb.PushMetricsResponse, error)
func (*Server) ReadFromFile ¶
ReadFromFile reads all data from file
func (*Server) RestoreValues ¶
RestoreValues restore metrics from file
func (*Server) SaveToFile ¶
SaveToFile saves metrics to file
func (*Server) StartServer ¶
func (srv *Server) StartServer(ctx context.Context, srvFlags *config.ServerFlags)
func (*Server) StopAsyncSaving ¶
func (srv *Server) StopAsyncSaving()
func (*Server) StopServer ¶
func (*Server) UpdateBatchJSONHandle ¶
func (srv *Server) UpdateBatchJSONHandle(w http.ResponseWriter, r *http.Request)
UpdateBatchJSONHandle godoc @Tags update @Summary Batch update array of metrics, data in JSON @Description Update existed metric or add new metric from JSON array of metrics @ID updateBatch @Accept json @Produce json @Param metrics body []metrics.Metric true "Array of metrics" @Success 200 {string} string "OK" @Failure 400 {string} string "Invalid type or value" @Failure 404 {string} string "Missing name of metric" @Failure 405 {string} string "Invalid request type" @Failure 500 {string} string "Internal error" @Router /updates/ [post]
Example ¶
client := &http.Client{} address := "localhost:8080" url := "http://" + address + "/updates/" mval := 34.5 mem := &metrics.Metric{ ID: "virtual_memory", MType: "gauge", Value: &mval, } cval := int64(12) cpu := &metrics.Metric{ ID: "cpu", MType: "counter", Delta: &cval, } arr := make([]metrics.Metric, 0) arr = append(arr, *mem) arr = append(arr, *cpu) bodyBuffer := new(bytes.Buffer) gzb := gzip.NewWriter(bodyBuffer) json.NewEncoder(gzb).Encode(arr) err := gzb.Close() if err != nil { fmt.Printf("Error encode request body: %v", err.Error()) return } request, err := http.NewRequest(http.MethodPost, url, bodyBuffer) if err != nil { fmt.Printf("Error request: %v", err.Error()) return } response, err := client.Do(request) if err != nil { fmt.Printf("Error response: %v", err.Error()) return } defer response.Body.Close() if response.StatusCode != http.StatusOK { fmt.Printf("Error response") return }
Output:
func (*Server) UpdateHandle ¶
func (srv *Server) UpdateHandle(w http.ResponseWriter, r *http.Request)
UpdateHandle godoc @Tags update @Summary Update existed metric or add new metric @Description Update existed metric or add new metric @ID update @Accept plain @Produce plain @Param type path string true "Metric type" @Param name path string true "Metric name" @Param value path number true "Metric value" @Success 200 {string} string "OK" @Failure 400 {string} string "Invalid type or value" @Failure 404 {string} string "Missing name of metric" @Failure 405 {string} string "Invalid request type" @Failure 500 {string} string "Internal error" @Router /update/{type}/{name}/{value} [post]
func (*Server) UpdateJSONHandle ¶
func (srv *Server) UpdateJSONHandle(w http.ResponseWriter, r *http.Request)
UpdateJSONHandle godoc @Tags update @Summary Update metric, data in JSON @Description Update existed metric or add new metric from JSON data @ID updateJSON @Accept json @Produce json @Param metric body []metrics.Metric true "Array of metrics" @Success 200 {string} string "OK" @Failure 400 {string} string "Invalid type or value" @Failure 404 {string} string "Missing name of metric" @Failure 405 {string} string "Invalid request type" @Failure 500 {string} string "Internal error" @Router /update/ [post]