Skip to content

Commit

Permalink
Add output json
Browse files Browse the repository at this point in the history
use slog package from golang 1.211 to output to different output by
default to a fancy and colourful one with tint library and let output to
json when running  under  service like Kubernetes or Systemd.
  • Loading branch information
chmouel committed Nov 14, 2023
1 parent e9d1174 commit dae0d4c
Show file tree
Hide file tree
Showing 339 changed files with 1,211 additions and 494 deletions.
11 changes: 6 additions & 5 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
module github.com/chmouel/gosmee

go 1.19
go 1.21

require (
github.com/go-chi/chi/v5 v5.0.10
github.com/lmittmann/tint v1.0.3
github.com/mattn/go-isatty v0.0.20
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d
github.com/mitchellh/mapstructure v1.5.0
github.com/r3labs/sse/v2 v2.10.0
github.com/urfave/cli/v2 v2.25.7
golang.org/x/crypto v0.14.0
golang.org/x/text v0.13.0
golang.org/x/crypto v0.15.0
golang.org/x/text v0.14.0
gotest.tools/v3 v3.5.1
)

Expand All @@ -21,7 +22,7 @@ require (
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
golang.org/x/net v0.17.0 // indirect
golang.org/x/sys v0.13.0 // indirect
golang.org/x/net v0.18.0 // indirect
golang.org/x/sys v0.14.0 // indirect
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
)
19 changes: 11 additions & 8 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk=
github.com/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/lmittmann/tint v1.0.3 h1:W5PHeA2D8bBJVvabNfQD/XW9HPLZK1XoPZH0cq8NouQ=
github.com/lmittmann/tint v1.0.3/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
Expand All @@ -30,23 +32,24 @@ github.com/urfave/cli/v2 v2.25.7/go.mod h1:8qnjx1vcq5s2/wpsqoZFndg2CE5tNFyrTvS6S
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU=
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
golang.org/x/crypto v0.15.0 h1:frVn1TEaCEaZcn3Tmd7Y2b5KKPaZ+I32Q2OA3kYp5TA=
golang.org/x/crypto v0.15.0/go.mod h1:4ChreQoLWfG3xLDer1WdlH5NdlQ3+mwnQq1YTKY+72g=
golang.org/x/net v0.0.0-20191116160921-f9c825593386/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
golang.org/x/net v0.18.0 h1:mIYleuAkSbHh0tCv7RvjL3F6ZVbLjq4+R7zbOn3Kokg=
golang.org/x/net v0.18.0/go.mod h1:/czyP5RqHAH4odGYxBJ1qz0+CE5WZ+2j1YgoEo8F2jQ=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=
golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
gopkg.in/cenkalti/backoff.v1 v1.1.0 h1:Arh75ttbsvlpVA7WtVpH4u9h6Zl46xuptxqLxPiSo4Y=
gopkg.in/cenkalti/backoff.v1 v1.1.0/go.mod h1:J6Vskwqd+OMVJl8C33mmtxTBs2gyzfv7UDAkHu8BrjI=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU=
gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU=
28 changes: 27 additions & 1 deletion gosmee/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ package gosmee

import (
"fmt"
"log/slog"
"net/url"
"os"
"strings"
"time"

_ "embed"

"github.com/lmittmann/tint"
"github.com/mattn/go-isatty"
"github.com/mgutz/ansi"
"github.com/urfave/cli/v2"
Expand Down Expand Up @@ -82,6 +85,22 @@ accessible endpoint and forward request to your local service`,
UsageText: "gosmee [command options] SMEE_URL LOCAL_SERVICE_URL",
Usage: "Make a client from the relay server to your local service",
Action: func(c *cli.Context) error {
nocolor := c.Bool("nocolor")
w := os.Stdout
logger := slog.New(tint.NewHandler(w, &tint.Options{
TimeFormat: time.RFC1123,
NoColor: !isatty.IsTerminal(w.Fd()),
}))
switch c.String("output") {
case "json":
logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
nocolor = true
case "pretty":
logger = logger

Check failure on line 99 in gosmee/app.go

View workflow job for this annotation

GitHub Actions / Lint

assign: self-assignment of logger to logger (govet)
default:
return fmt.Errorf("invalid output format %s", c.String("output"))
}

var smeeURL, targetURL string
if os.Getenv("GOSMEE_URL") != "" && os.Getenv("GOSMEE_TARGET_URL") != "" {
smeeURL = os.Getenv("GOSMEE_URL")
Expand All @@ -104,7 +123,7 @@ accessible endpoint and forward request to your local service`,
ansi.DisableColors(true)
decorate = false
}
if c.Bool("nocolor") {
if nocolor {
ansi.DisableColors(true)
decorate = false
}
Expand All @@ -118,6 +137,7 @@ accessible endpoint and forward request to your local service`,
channel: c.String("channel"),
targetCnxTimeout: c.Int("target-connection-timeout"),
insecureTLSVerify: c.Bool("insecure-skip-tls-verify"),
logger: logger,
}
err := cfg.clientSetup()
return err
Expand All @@ -129,6 +149,12 @@ accessible endpoint and forward request to your local service`,
Usage: "gosmee channel to listen, only useful when you are not use smee.io",
Value: smeeChannel,
},
&cli.StringFlag{
Name: "output",
Usage: `Output format, one of "json", "pretty"`,
Value: "pretty",
Aliases: []string{"o"},
},
&cli.StringSliceFlag{
Name: "ignore-event",
Aliases: []string{"I"},
Expand Down
45 changes: 22 additions & 23 deletions gosmee/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"os"
"path/filepath"
Expand Down Expand Up @@ -45,6 +46,7 @@ type goSmee struct {
channel string
targetCnxTimeout int
insecureTLSVerify bool
logger *slog.Logger
}

type payloadMsg struct {
Expand Down Expand Up @@ -134,7 +136,8 @@ func (c goSmee) parse(now time.Time, data []byte) (payloadMsg, error) {
// timestamp payload value is in milliseconds since the Epoch
tsInt, err := strconv.ParseInt(pv, 10, 64)
if err != nil {
fmt.Fprintf(os.Stdout, "%s cannot convert timestamp to int64, %s\n", ansi.Color("ERROR", "red+b"), err.Error())
s := fmt.Sprintf("%s cannot convert timestamp to int64, %s", ansi.Color("ERROR", "red+b"), err.Error())
c.logger.Error(s)
} else {
dt = time.Unix(tsInt/int64(1000), (tsInt%int64(1000))*int64(1000000)).UTC()
}
Expand All @@ -147,7 +150,8 @@ func (c goSmee) parse(now time.Time, data []byte) (payloadMsg, error) {
if len(c.ignoreEvents) > 0 && pm.eventType != "" {
for _, v := range c.ignoreEvents {
if v == pm.eventType {
fmt.Fprintf(os.Stdout, "%sskipping event %s as requested\n", c.emoji("!", "blue+b"), pm.eventType)
s := fmt.Sprintf("%sskipping event %s as requested", c.emoji("!", "blue+b"), pm.eventType)
c.logger.Error(s)
return payloadMsg{}, nil
}
}
Expand Down Expand Up @@ -192,7 +196,7 @@ func (c goSmee) saveData(pm payloadMsg) error {

shscript := fmt.Sprintf("%s/%s.sh", c.saveDir, fbasepath)

fmt.Fprintf(os.Stdout, "%s%s and %s has been saved\n", c.emoji("⌁", "yellow+b"), shscript, jsonfile)
c.logger.Info(fmt.Sprintf("%s%s and %s has been saved", c.emoji("⌁", "yellow+b"), shscript, jsonfile))
s, err := os.Create(shscript)
if err != nil {
return err
Expand Down Expand Up @@ -260,13 +264,15 @@ func (c goSmee) replayData(pm payloadMsg) error {
if resp.StatusCode > 299 {
msg = fmt.Sprintf("%s, error: %s", msg, resp.Status)
}
fmt.Fprintf(os.Stdout, "%s%s\n", c.emoji("•", "magenta+b"), msg)
s := fmt.Sprintf("%s%s", c.emoji("•", "magenta+b"), msg)
c.logger.Info(s)
return nil
}

func (c goSmee) clientSetup() error {
version := strings.TrimSpace(string(Version))
fmt.Fprintf(os.Stdout, "%sStarting gosmee version: %s\n", c.emoji("⇉", "green+b"), version)
s := fmt.Sprintf("%sStarting gosmee version: %s", c.emoji("⇉", "green+b"), version)
c.logger.Info(s)
client := sse.NewClient(c.smeeURL, sse.ClientMaxBufferSize(1<<20))
client.Headers["User-Agent"] = fmt.Sprintf("gosmee/%s", version)
// this is to get nginx to work
Expand All @@ -280,36 +286,29 @@ func (c goSmee) clientSetup() error {
nowStr := now.Format(tsFormat)

if string(msg.Event) == "ready" || string(msg.Data) == "ready" {
fmt.Fprintf(os.Stdout,
"%s %sForwarding %s to %s\n",
nowStr,
c.emoji("✓", "yellow+b"),
ansi.Color(c.smeeURL, "green+u"),
ansi.Color(c.targetURL, "green+u"))
s := fmt.Sprintf("%s %sForwarding %s to %s", nowStr, c.emoji("✓", "yellow+b"), ansi.Color(c.smeeURL, "green+u"), ansi.Color(c.targetURL, "green+u"))
c.logger.Info(s)
return
}

if string(msg.Event) == "ping" {
return
} /* Apparently github sends
* a ping every minute but it's not
* documented anywhere for some reason
*/
}

pm, err := c.parse(now, msg.Data)
if err != nil {
fmt.Fprintf(os.Stdout,
"%s %s parsing message %s\n",
s := fmt.Sprintf("%s %s parsing message %s",
nowStr,
ansi.Color("ERROR", "red+b"),
err.Error())
c.logger.Error(s)
return
}
if len(pm.headers) == 0 {
fmt.Fprintf(os.Stdout,
"%s %s no headers found in message\n",
s := fmt.Sprintf("%s %s no headers found in message",
nowStr,
ansi.Color("ERROR", "red+b"))
c.logger.Error(s)
return
}
headers := ""
Expand All @@ -321,23 +320,23 @@ func (c goSmee) clientSetup() error {
if c.saveDir != "" {
err := c.saveData(pm)
if err != nil {
fmt.Fprintf(os.Stdout,
"%s %s saving message with headers '%s' - %s\n",
s := fmt.Sprintf("%s %s saving message with headers '%s' - %s",
nowStr,
ansi.Color("ERROR", "red+b"),
headers,
err.Error())
c.logger.Error(s)
return
}
}
if !c.noReplay {
if err := c.replayData(pm); err != nil {
fmt.Fprintf(os.Stdout,
"%s %s forwarding message with headers '%s' - %s\n",
s := fmt.Sprintf("%s %s forwarding message with headers '%s' - %s",
nowStr,
ansi.Color("ERROR", "red+b"),
headers,
err.Error())
c.logger.Error(s)
return
}
}
Expand Down
2 changes: 2 additions & 0 deletions misc/com.chmouel.gosmee.plist
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
<array>
<string>gosmee</string>
<string>client</string>
<string>--output</string>
<string>json</string>
<string>https://smee.io/aBcDeF</string>
<string>https://localhost:8080</string>
</array>
Expand Down
2 changes: 1 addition & 1 deletion misc/gosmee.service
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
Description=Gosmee Forward

[Service]
ExecStart=gosmee client https://smee.io/abcdef http://localhost:8080
ExecStart=gosmee client --output=json https://smee.io/abcdef http://localhost:8080
EnvironmentFile=/etc/gosmee.env

[Install]
Expand Down
2 changes: 2 additions & 0 deletions misc/kubernetes-deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ spec:
args:
[
"client",
"--output",
"json",
"--saveDir",
"/tmp/save",
"https://yousmee.url",
Expand Down
21 changes: 21 additions & 0 deletions vendor/github.com/lmittmann/tint/LICENSE

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit dae0d4c

Please sign in to comment.