Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

iter4: Аргументы командной строки прицепил #4

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions cmd/agent/flags.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package main

import (
"flag"
"github.com/kosalnik/metrics/internal/config"
)

func parseFlags(c *config.AgentConfig) {
flag.StringVar(&c.CollectorAddress, "a", "127.0.0.1:8080", "address server endpoint")
flag.Int64Var(&c.PoolInterval, "p", 2, "Pool interval (seconds)")
flag.Int64Var(&c.ReportInterval, "r", 10, "Report interval (seconds)")
flag.Parse()
}
3 changes: 2 additions & 1 deletion cmd/agent/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

func main() {
cfg := config.NewConfig()
app := client.NewClient(cfg.Client)
parseFlags(&cfg.Agent)
app := client.NewClient(cfg.Agent)
app.Run()
}
11 changes: 11 additions & 0 deletions cmd/server/flags.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package main

import (
"flag"
"github.com/kosalnik/metrics/internal/config"
)

func parseFlags(c *config.ServerConfig) {
flag.StringVar(&c.Address, "a", ":8080", "server endpoint (ip:port)")
flag.Parse()
}
5 changes: 4 additions & 1 deletion cmd/server/main.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package main

import (
"github.com/kosalnik/metrics/internal/config"
"github.com/kosalnik/metrics/internal/server"
)

func main() {
app := server.NewApp()
cfg := config.NewConfig()
parseFlags(&cfg.Server)
app := server.NewApp(cfg.Server)
err := app.Serve()
if err != nil {
panic(err)
Expand Down
15 changes: 9 additions & 6 deletions internal/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,29 @@ import (
type Client struct {
mu sync.Mutex
client *http.Client
config *config.ClientConfig
config *config.AgentConfig
gauge map[string]float64
poolCount int64
}

func NewClient(config config.ClientConfig) *Client {
func NewClient(config config.AgentConfig) *Client {
return &Client{
client: http.DefaultClient,
config: &config,
}
}

func (c *Client) Run() {
log.Printf("Pool interval: %d\n", c.config.PoolInterval)
log.Printf("Report interval: %d\n", c.config.ReportInterval)
log.Printf("Collector address: %s\n", c.config.CollectorAddress)
go c.pool()
c.push()
}

func (c *Client) push() {
for {
time.Sleep(c.config.ReportInterval)
time.Sleep(time.Duration(c.config.ReportInterval) * time.Second)
c.mu.Lock()
log.Println("Push")
if c.gauge != nil {
Expand All @@ -55,12 +58,12 @@ func (c *Client) pool() {
c.poolCount = c.poolCount + 1
log.Println(c.poolCount)
c.mu.Unlock()
time.Sleep(c.config.PoolInterval)
time.Sleep(time.Duration(c.config.PoolInterval) * time.Second)
}
}

func (c *Client) sendGauge(k string, v float64) {
r, err := c.client.Post(fmt.Sprintf("%s/update/gauge/%s/%v", c.config.CollectorAddress, k, v), "text/plain", nil)
r, err := c.client.Post(fmt.Sprintf("http://%s/update/gauge/%s/%v", c.config.CollectorAddress, k, v), "text/plain", nil)
if err != nil {
log.Printf("fail push. %s", err.Error())
}
Expand All @@ -70,7 +73,7 @@ func (c *Client) sendGauge(k string, v float64) {
}

func (c *Client) sendCounter(k string, v int64) {
r, err := c.client.Post(fmt.Sprintf("%s/update/counter/%s/%v", c.config.CollectorAddress, k, v), "text/plain", nil)
r, err := c.client.Post(fmt.Sprintf("http://%s/update/counter/%s/%v", c.config.CollectorAddress, k, v), "text/plain", nil)
if err != nil {
log.Printf("Fail push: %s", err.Error())
}
Expand Down
30 changes: 20 additions & 10 deletions internal/config/config.go
Original file line number Diff line number Diff line change
@@ -1,23 +1,33 @@
package config

import "time"

type Config struct {
Client ClientConfig
Agent AgentConfig
Server ServerConfig
}

type ClientConfig struct {
type AgentConfig struct {
// Адрес сервера, куда клиент будет посылать метрики
CollectorAddress string
PoolInterval time.Duration
ReportInterval time.Duration
// Время между сборами метрик
PoolInterval int64
// Время между отправками метрик на сервер
ReportInterval int64
}

type ServerConfig struct {
// ip:host, которые слушает сервер
Address string
}

func NewConfig() *Config {
return &Config{
Client: ClientConfig{
CollectorAddress: "http://127.0.0.1:8080",
PoolInterval: time.Duration(time.Second * 2),
ReportInterval: time.Duration(time.Second * 10),
Agent: AgentConfig{
CollectorAddress: "127.0.0.1:8080",
PoolInterval: 2,
ReportInterval: 10,
},
Server: ServerConfig{
Address: ":8080",
},
}
}
14 changes: 10 additions & 4 deletions internal/handlers/get_all.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"fmt"
"github.com/kosalnik/metrics/internal/storage"
"net/http"
"sort"
"strings"
)

type GetAllHandler struct {
Expand All @@ -20,11 +22,15 @@ func NewGetAllHandler(s storage.Storage) func(res http.ResponseWriter, req *http
func (h *GetAllHandler) Handler() func(w http.ResponseWriter, req *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
items := h.storage.GetPlain()
fmt.Println(items)
var res = []string{}
for k, v := range items {
_, err := fmt.Fprintf(w, "%s = %s\n", k, v)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
res = append(res, fmt.Sprintf("%s = %s", k, v))
}
sort.Strings(res)
_, err := fmt.Fprint(w, strings.Join(res, "\n"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
5 changes: 3 additions & 2 deletions internal/handlers/get_all_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package handlers_test

import (
"github.com/kosalnik/metrics/internal/config"
"github.com/kosalnik/metrics/internal/server"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand All @@ -11,7 +12,7 @@ import (
)

func TestGetAllHandler(t *testing.T) {
app := server.NewApp()
app := server.NewApp(config.ServerConfig{})
s := app.Storage
r := app.GetRouter()
s.IncCounter("c1", 5)
Expand All @@ -25,6 +26,6 @@ func TestGetAllHandler(t *testing.T) {
assert.Equal(t, http.StatusOK, res.StatusCode)
err = res.Body.Close()
require.NoError(t, err)
expected := "g1 = 13.1\nc1 = 5\n"
expected := "c1 = 5\ng1 = 13.1"
assert.Equal(t, expected, string(content))
}
3 changes: 2 additions & 1 deletion internal/handlers/get_one_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package handlers_test

import (
"github.com/kosalnik/metrics/internal/config"
"github.com/kosalnik/metrics/internal/server"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand All @@ -24,7 +25,7 @@ func TestGetHandler(t *testing.T) {
{"invalid metric type", "/value/unk/u3", "Not Found\n", http.StatusNotFound},
}

app := server.NewApp()
app := server.NewApp(config.ServerConfig{})
s := app.Storage
r := app.GetRouter()
s.IncCounter("c1", 5)
Expand Down
3 changes: 2 additions & 1 deletion internal/handlers/update_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package handlers_test

import (
"github.com/kosalnik/metrics/internal/config"
"github.com/kosalnik/metrics/internal/server"
"github.com/kosalnik/metrics/internal/storage"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -80,7 +81,7 @@ func TestUpdateHandler_Handle(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
app := server.NewApp()
app := server.NewApp(config.ServerConfig{})
r := app.GetRouter()
srv := httptest.NewServer(r)
response, err := srv.Client().Post(srv.URL+tt.path, "text/plain", nil)
Expand Down
9 changes: 7 additions & 2 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,28 @@ package server

import (
"github.com/go-chi/chi/v5"
"github.com/kosalnik/metrics/internal/config"
"github.com/kosalnik/metrics/internal/handlers"
"github.com/kosalnik/metrics/internal/storage"
"log"
"net/http"
)

type App struct {
Storage storage.Storage
config config.ServerConfig
}

func NewApp() *App {
func NewApp(cfg config.ServerConfig) *App {
return &App{
Storage: storage.NewStorage(),
config: cfg,
}
}

func (app *App) Serve() error {
return http.ListenAndServe(`:8080`, app.GetRouter())
log.Println("Listen " + app.config.Address)
return http.ListenAndServe(app.config.Address, app.GetRouter())
}

func (app *App) GetRouter() chi.Router {
Expand Down
Loading