-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmain.go
108 lines (97 loc) · 2.06 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"strings"
"github.com/urfave/cli"
)
var (
DefaultSocketLocation = "/tmp/log.sock"
VERSION = "dev"
)
// Client structure is used to store the server info
type Client struct {
SocketLocation string
httpc *http.Client
}
func main() {
app := cli.NewApp()
app.Version = VERSION
app.Usage = "Dynamically change loglevel"
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "set",
Usage: "Set loglevel",
},
cli.StringFlag{
Name: "socket-location",
EnvVar: "LOG_SOCKET_LOCATION",
Value: DefaultSocketLocation,
},
}
app.Action = run
err := app.Run(os.Args)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func NewClient(c *cli.Context) *Client {
client := &Client{
SocketLocation: c.String("socket-location"),
}
client.httpc = &http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", client.SocketLocation)
},
},
}
return client
}
func run(c *cli.Context) error {
client := NewClient(c)
if c.String("set") != "" {
err := client.setLogLevel(c.String("set"))
if err != nil {
return fmt.Errorf("Error when setting loglevel: %s", err)
}
return nil
}
err := client.getLogLevel()
if err != nil {
return fmt.Errorf("Error when getting loglevel: %s", err)
}
return nil
}
func (client *Client) setLogLevel(level string) error {
response, err := client.httpc.Post("http://unix/v1/loglevel",
"application/x-www-form-urlencoded",
strings.NewReader(fmt.Sprintf("level=%v", level)))
if err != nil {
return err
}
if response.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
return errors.New(strings.TrimRight(string(body), "\n"))
}
io.Copy(os.Stdout, response.Body)
return nil
}
func (client *Client) getLogLevel() error {
response, err := client.httpc.Get("http://unix/v1/loglevel")
if err != nil {
return err
}
io.Copy(os.Stdout, response.Body)
return nil
}