Skip to content

Commit

Permalink
refactor: rewrite in go
Browse files Browse the repository at this point in the history
  • Loading branch information
jesusprubio committed Apr 21, 2024
0 parents commit ba2b993
Show file tree
Hide file tree
Showing 18 changed files with 748 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
version: 2
updates:
- package-ecosystem: "gomod"
directory: "/" # Location of go.mod
schedule:
interval: "daily"
30 changes: 30 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
on:
push:
branches:
- main
pull_request:

name: CI

env:
TASK_X_REMOTE_TASKFILES: 1

jobs:
test:
name: Unit tests
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v4
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: "1.22.2"
- name: Install Task
uses: arduino/setup-task@v2
- name: Install dependencies
run: task dep
- name: Run linters
run: task lint
- name: Run tests
run: task test
24 changes: 24 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Mac OS X Finder files.
.DS_Store
# Test binary, built with `go test -c`
*.test
# Go coverage tool
*.out
# Dependencies
vendor/
# Go workspace file
go.work
# Vendoring
vendor/
# Goreleaser
dist/
# Taskfile (remote)
.task/
# VS Code
.vscode/
33 changes: 33 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Developer Guide

## Dependencies

- [Task](https://taskfile.dev/installation/)
- Linters:
```sh
task dep
```

## Develop

```sh
task
```

## Tests, linters and format

```sh
task lint
task test
task fmt
```

## Build

```sh
task build
```

## Release

TODO
21 changes: 21 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright Jesús Rubio <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
47 changes: 47 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<h1 align="center">up</h1>
<div align="center">
<img alt="Logo" src="https://media.giphy.com/media/pYyFAHLW0zJL2/giphy.gif" width="40%">
</div>

Troubleshoot problems with your Internet connection based om different
[protocols](pkg/protocol.go) and [public servers](pkg/servers.go).

[![GoDoc][doc-img]][doc] [![Build Status][ci-img]][ci] ![License](https://img.shields.io/github/license/jesusprubio/up)

## Install

```sg
go install github.com/jesusprubio/up@latest
```

### Dependencies

- [Go](https://go.dev/doc/install) stable version.

## Use

The default behavior is to verify all the [supported protocols](pkg/protocol.go)
against a randomly selected [public server](pkg/servers.go) for each one.

```sh
up
```

This will display help for the tool.

```sh
up -h
```

### Library

Check [the examples](examples) to see how to use this project in your own code.

## License

This project is under the MIT License. See the [LICENSE](LICENSE) file for the full license text.

[doc-img]: https://pkg.go.dev/badge/github.com/jesusprubio/up
[doc]: https://pkg.go.dev/github.com/jesusprubio/up
[ci-img]: https://github.com/jesusprubio/up/workflows/CI/badge.svg
[ci]: https://github.com/jesusprubio/up/workflows/go.yml
42 changes: 42 additions & 0 deletions Taskfile.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
version: "3"

tasks:
default:
deps: [dev]

dev:
summary: "Development mode"
cmd: go run cmd/main.go

build:
summary: "Build application"
cmd: go build -o dist/up cmd/main.go

clean:
summary: "Clean the project"
cmd: go clean

dep:
summary: "Install dev dependencies"
cmds:
# Linters.
- go install honnef.co/go/tools/cmd/staticcheck@latest
- go install github.com/securego/gosec/v2/cmd/gosec@latest
# Formatters.
- go install github.com/segmentio/golines@latest

fmt:
summary: "Format the code"
# Runs `go fmt` before finishing.
cmd: golines -m 80 --shorten-comments -w .

lint:
summary: "Run linters"
cmds:
- go vet ./...
- staticcheck ./...
- gosec -fmt=golint -quiet ./...

test:
summary: "Run tests"
cmd: go test -v ./...
156 changes: 156 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
package main

import (
"context"
"encoding/json"
"flag"
"fmt"
"log/slog"
"os"
"os/signal"
"syscall"
"time"

"github.com/fatih/color"
"github.com/jesusprubio/up/pkg"
)

const (
appName = "up"
appDesc = `
Troubleshoot problems with your Internet connection based on different
protocols and public servers.
OUTPUT
Details about each request:
{Protocol used} {Response time} {Remote server} {Extra info}
EXIT STATUS
This utility exits with one of the following values:
0 At least one response was heard.
2 The transmission was successful but no responses were received.
1 Any other value An error occurred.
`
)

// TODO: Support passing a custom remote server as an argument.

// CLI initialization.
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Input options.
flagProto := flag.String(
"p",
"",
fmt.Sprintf("Use only one protocol: %v", pkg.Protocols),
)
flagCount := flag.Uint("c", 0, "Number of iterations. (0 = infinite)")
flagTimeout := flag.Duration("t",
5*time.Second,
"Time to wait for a response",
)
flagDelay := flag.Duration(
"d",
500*time.Millisecond,
"Delay between requests",
)
flagStop := flag.Bool("s", false, "Stop after the first successful request")
// Output options.
flagJSONOutput := flag.Bool("j", false, "Output in JSON format")
flagNoColor := flag.Bool("nc", false, "Disable color output")
flagVerbose := flag.Bool("v", false, "Verbose output")
flagHelp := flag.Bool("h", false, "Show app documentation")
flag.Parse()
lvl := new(slog.LevelVar)
lvl.Set(slog.LevelError)
// Only used for debugging.
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
Level: lvl,
}))
if *flagVerbose {
lvl.Set(slog.LevelDebug)
}
logger.Debug("Running",
"protocol", *flagProto,
"count", *flagCount,
"timeout", *flagTimeout,
"delay", *flagDelay,
"stop", *flagStop,
"json", *flagJSONOutput,
"no-color", *flagNoColor,
"verbose", *flagVerbose,
"help", *flagHelp,
)
protocols := pkg.Protocols
if *flagProto != "" {
protocol := pkg.ProtocolByID(*flagProto)
if protocol == nil {
fatal(fmt.Errorf("unknown protocol: %s", *flagProto))
}
protocols = []*pkg.Protocol{protocol}
}
logger.Info("Running", "protocols", protocols, "count", *flagCount)
if *flagHelp {
fmt.Fprintf(os.Stderr, "%s\n", appDesc)
flag.Usage()
os.Exit(1)
}
if *flagNoColor {
color.NoColor = true
}
// To wait for termination signals.
// - 'Interrupt': Ctrl+C from terminal.
// - 'SIGTERM': Sent from Kubernetes.
sigCh := make(chan os.Signal, 1)
defer close(sigCh)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
go func() {
logger.Debug("Listening for termination signals")
<-sigCh
logger.Debug("Termination signal received")
cancel()
}()
probe := pkg.Probe{
Protocols: protocols,
Count: *flagCount,
Delay: *flagDelay,
Timeout: *flagTimeout,
Logger: logger,
ReportCh: make(chan *pkg.Report),
}
go func() {
logger.Debug("Listening for reports")
for report := range probe.ReportCh {
logger.Debug("New report", "report", *report)
var line string
if *flagJSONOutput {
reportJSON, err := json.Marshal(report)
if err != nil {
fatal(fmt.Errorf("marshaling report: %w", err))
}
line = string(reportJSON)
} else {
line = report.String()
}
fmt.Println(line)
if report.Error == nil {
if *flagStop {
logger.Debug("Stop requested")
cancel()
}
}
}
}()
logger.Debug("Running", "setup", probe)
err := probe.Run(ctx)
if err != nil {
fatal(err)
}
logger.Debug("Bye!")
}

func fatal(err error) {
fmt.Fprintf(os.Stderr, "%s: %s\n", appName, err)
os.Exit(1)
}
2 changes: 2 additions & 0 deletions examples/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Package examples provides examples of how to use this project as a library.
package examples
3 changes: 3 additions & 0 deletions examples/probe.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package examples

// TODO
11 changes: 11 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module github.com/jesusprubio/up

go 1.22.2

require github.com/fatih/color v1.16.0

require (
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
golang.org/x/sys v0.14.0 // indirect
)
11 changes: 11 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM=
github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE=
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=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
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.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=
golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
Loading

0 comments on commit ba2b993

Please sign in to comment.