8 Commits

Author SHA1 Message Date
3be7ddb36b ensure we return closer from run() 2026-02-16 00:11:50 +00:00
c22b07808f upd imgs 2026-02-15 19:37:41 +00:00
c015770c2c add v0.4.0 to CHANGELOG 2026-02-15 18:35:52 +00:00
cd15e89837 add macos target to goreleaser config 2026-02-15 18:31:25 +00:00
c3e8013c4f make the example implementation a little more useful with a timeouts map. 2026-02-15 18:29:14 +00:00
89dd2d2eb1 replace exitOnError with deferred exit function.
this ensures the closer() cleanup function is always called
2026-02-15 18:24:59 +00:00
c04301562e add macos target to Taskfile/makefile 2026-02-15 17:21:47 +00:00
e25104091d add golangci-lint config + action 2026-02-15 17:21:05 +00:00
10 changed files with 282 additions and 39 deletions

30
.github/workflows/golang-ci.yml vendored Normal file
View File

@@ -0,0 +1,30 @@
name: CI
on:
push:
branches: ['main']
paths:
- '**.go'
pull_request:
branches: ['main']
paths:
- '**.go'
jobs:
lint:
name: Lint
runs-on: ubuntu-latest
if: github.event_name == 'pull_request'
timeout-minutes: 3
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: '1.24'
- name: golangci-lint
uses: golangci/golangci-lint-action@v9
with:
version: v2.6.0
args: --config .golangci.yml

142
.golangci.yml Normal file
View File

@@ -0,0 +1,142 @@
version: '2'
run:
timeout: 3m
tests: true
go: '1.24'
linters:
disable: [errcheck, errorlint, godot, revive, staticcheck]
enable:
# Default enabled linters
- errcheck # Check for unchecked errors
- govet # Go's built-in vetting tool
- ineffassign # Detect ineffectual assignments
- staticcheck # Advanced static analysis
- unused # Check for unused code
# Additional useful linters
- misspell # Detect common misspellings
- unparam # Check for unused function parameters
- gosec # Security checks
- asciicheck # Check for non-ASCII characters
- errname # Check error variable names
- godot # Check for missing periods in comments
- revive # Highly configurable linter for style and correctness
- gocritic # Detect code issues and suggest improvements
- gocyclo # Check for cyclomatic complexity
- dupl # Check for code duplication
- predeclared # Check for shadowing of predeclared identifiers
- copyloopvar # Check for loop variable capture in goroutines
- errorlint # Check for common mistakes in error handling
- goconst # Check for repeated strings that could be constants
- gosmopolitan # Check for non-portable code
settings:
misspell:
locale: UK
errcheck:
check-type-assertions: true
check-blank: true
exclude-functions:
- fmt.Fprintf
- fmt.Fprintln
- fmt.Printf
- fmt.Println
- fmt.Errorf
revive:
severity: warning
rules:
# Code quality and style
- name: exported
arguments:
- 'checkPrivateReceivers'
- 'sayRepetitiveInsteadOfStutters'
- name: var-naming
- name: package-comments
- name: range-val-in-closure
- name: time-naming
- name: context-as-argument
- name: context-keys-type
- name: dot-imports
- name: empty-block
- name: error-return
- name: error-strings
- name: error-naming
- name: if-return
- name: increment-decrement
- name: indent-error-flow
- name: receiver-naming
- name: redefines-builtin-id
- name: superfluous-else
- name: unexported-return
- name: unreachable-code
- name: unused-parameter
- name: var-declaration
- name: blank-imports
- name: range
# Disabled rules (can be enabled if needed)
# - name: line-length-limit
# arguments: [120]
# - name: function-length
# arguments: [50, 0]
# - name: cyclomatic
# arguments: [10]
gosec:
excludes:
- G104 # Duplicated errcheck checks
- G115 # integer overflow conversion int -> uint32
exclusions:
warn-unused: false
rules:
# Exclude some linters from running on tests files.
- path: _test\.go
linters:
- gocyclo
- errcheck
- dupl
- gosec
paths:
- vendor
# Formatters configuration
formatters:
# Enable specific formatters
enable:
- gofumpt # Stricter gofmt alternative
- goimports # Organizes imports
- gci # Controls import order/grouping
- golines # Enforces line length
# Formatter-specific settings
settings:
goimports:
local-prefixes: [github.com/onyx-and-iris/q3rcon]
gci:
# Define import sections order
sections:
- standard # Standard library
- default # Everything else
- prefix(github.com/onyx-and-iris/q3rcon) # Current module
gofumpt:
extra-rules: true # Enable additional formatting rules
exclusions:
warn-unused: true
paths:
- vendor
issues:
# Limit the number of same issues reported to avoid spam
max-same-issues: 50
# Limit the number of issues per linter to keep output manageable
max-issues-per-linter: 100

View File

@@ -22,6 +22,7 @@ builds:
goos: goos:
- linux - linux
- windows - windows
- darwin
goarch: goarch:
- amd64 - amd64

View File

@@ -11,6 +11,18 @@ Before any major/minor/patch bump all unit tests will be run to verify they pass
- [x] - [x]
# [0.4.0] - 2026-02-15
### Added
- macos build to releases
### Changed
- exitOnError() removed in favour of a [deferred exit function](https://github.com/onyx-and-iris/q3rcon/blob/cd15e8983726177d6edd985a8bf3d7f4e0d7f346/cmd/q3rcon/main.go#L21), this ensures the closer() cleanup function is always called.
- the included CLI now uses a [timeouts map](https://github.com/onyx-and-iris/q3rcon/blob/cd15e8983726177d6edd985a8bf3d7f4e0d7f346/cmd/q3rcon/main.go#L109).
- even though this is only an example implementation it should still be basically usable.
# [0.3.0] - 2025-04-05 # [0.3.0] - 2025-04-05
### Changed ### Changed

View File

@@ -7,6 +7,7 @@ vars:
WINDOWS: '{{.BIN_DIR}}/{{.PROGRAM}}_windows_amd64.exe' WINDOWS: '{{.BIN_DIR}}/{{.PROGRAM}}_windows_amd64.exe'
LINUX: '{{.BIN_DIR}}/{{.PROGRAM}}_linux_amd64' LINUX: '{{.BIN_DIR}}/{{.PROGRAM}}_linux_amd64'
MACOS: '{{.BIN_DIR}}/{{.PROGRAM}}_darwin_amd64'
GIT_COMMIT: GIT_COMMIT:
sh: git log -n 1 --format=%h sh: git log -n 1 --format=%h
@@ -22,6 +23,7 @@ tasks:
cmds: cmds:
- task: build-windows - task: build-windows
- task: build-linux - task: build-linux
- task: build-macos
vet: vet:
desc: Vet the code desc: Vet the code
@@ -38,11 +40,19 @@ tasks:
desc: Build the q3rcon project for Windows desc: Build the q3rcon project for Windows
cmds: cmds:
- GOOS=windows GOARCH=amd64 go build -o {{.WINDOWS}} -ldflags="-X main.Version={{.GIT_COMMIT}}" ./cmd/{{.PROGRAM}}/ - GOOS=windows GOARCH=amd64 go build -o {{.WINDOWS}} -ldflags="-X main.Version={{.GIT_COMMIT}}" ./cmd/{{.PROGRAM}}/
internal: true
build-linux: build-linux:
desc: Build the q3rcon project for Linux desc: Build the q3rcon project for Linux
cmds: cmds:
- GOOS=linux GOARCH=amd64 go build -o {{.LINUX}} -ldflags="-X main.Version={{.GIT_COMMIT}}" ./cmd/{{.PROGRAM}}/ - GOOS=linux GOARCH=amd64 go build -o {{.LINUX}} -ldflags="-X main.Version={{.GIT_COMMIT}}" ./cmd/{{.PROGRAM}}/
internal: true
build-macos:
desc: Build the q3rcon project for macOS
cmds:
- GOOS=darwin GOARCH=amd64 go build -o {{.MACOS}} -ldflags="-X main.Version={{.GIT_COMMIT}}" ./cmd/{{.PROGRAM}}/
internal: true
test: test:
desc: Run tests desc: Run tests

View File

@@ -7,18 +7,35 @@ import (
"io" "io"
"os" "os"
"strings" "strings"
"time"
"github.com/onyx-and-iris/q3rcon"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/onyx-and-iris/q3rcon"
) )
func exitOnError(err error) { func main() {
_, _ = fmt.Fprintf(os.Stderr, "Error: %s\n", err) var exitCode int
os.Exit(1)
// Defer exit with the final exit code
defer func() {
if exitCode != 0 {
os.Exit(exitCode)
}
}()
closer, err := run()
if closer != nil {
defer closer()
}
if err != nil {
log.Error(err)
exitCode = 1
}
} }
func main() { // run executes the main logic of the application and returns a cleanup function and an error if any.
func run() (func(), error) {
var ( var (
host string host string
port int port int
@@ -30,9 +47,19 @@ func main() {
flag.StringVar(&host, "host", "localhost", "hostname of the gameserver") flag.StringVar(&host, "host", "localhost", "hostname of the gameserver")
flag.StringVar(&host, "h", "localhost", "hostname of the gameserver (shorthand)") flag.StringVar(&host, "h", "localhost", "hostname of the gameserver (shorthand)")
flag.IntVar(&port, "port", 28960, "port on which the gameserver resides, default is 28960") flag.IntVar(&port, "port", 28960, "port on which the gameserver resides, default is 28960")
flag.IntVar(&port, "p", 28960, "port on which the gameserver resides, default is 28960 (shorthand)") flag.IntVar(
&port,
"p",
28960,
"port on which the gameserver resides, default is 28960 (shorthand)",
)
flag.StringVar(&rconpass, "rconpass", os.Getenv("RCON_PASS"), "rcon password of the gameserver") flag.StringVar(&rconpass, "rconpass", os.Getenv("RCON_PASS"), "rcon password of the gameserver")
flag.StringVar(&rconpass, "r", os.Getenv("RCON_PASS"), "rcon password of the gameserver (shorthand)") flag.StringVar(
&rconpass,
"r",
os.Getenv("RCON_PASS"),
"rcon password of the gameserver (shorthand)",
)
flag.BoolVar(&interactive, "interactive", false, "run in interactive mode") flag.BoolVar(&interactive, "interactive", false, "run in interactive mode")
flag.BoolVar(&interactive, "i", false, "run in interactive mode") flag.BoolVar(&interactive, "i", false, "run in interactive mode")
@@ -44,53 +71,69 @@ func main() {
level, err := log.ParseLevel(loglevel) level, err := log.ParseLevel(loglevel)
if err != nil { if err != nil {
exitOnError(fmt.Errorf("invalid log level: %s", loglevel)) return nil, fmt.Errorf("invalid log level: %s", loglevel)
} }
log.SetLevel(level) log.SetLevel(level)
if port < 1024 || port > 65535 { if port < 1024 || port > 65535 {
exitOnError(fmt.Errorf("invalid port value, got: (%d) expected: in range 1024-65535", port)) return nil, fmt.Errorf("invalid port value, got: (%d) expected: in range 1024-65535", port)
} }
if len(rconpass) < 8 { if len(rconpass) < 8 {
exitOnError(fmt.Errorf("invalid rcon password, got: (%s) expected: at least 8 characters", rconpass)) return nil, fmt.Errorf(
"invalid rcon password, got: (%s) expected: at least 8 characters",
rconpass,
)
} }
rcon, err := connectRcon(host, port, rconpass) client, closer, err := connectRcon(host, port, rconpass)
if err != nil { if err != nil {
exitOnError(err) return nil, fmt.Errorf("failed to connect to rcon: %w", err)
}
defer rcon.Close()
if !interactive {
runCommands(flag.Args(), rcon)
return
} }
fmt.Printf("Enter 'Q' to exit.\n>> ") if interactive {
err = interactiveMode(rcon, os.Stdin) fmt.Printf("Enter 'Q' to exit.\n>> ")
if err != nil { err := interactiveMode(client, os.Stdin)
exitOnError(err) if err != nil {
return closer, fmt.Errorf("interactive mode error: %w", err)
}
return closer, nil
} }
commands := flag.Args()
if len(commands) == 0 {
log.Debug("no commands provided, defaulting to 'status'")
commands = append(commands, "status")
}
runCommands(client, commands)
return closer, nil
} }
func connectRcon(host string, port int, password string) (*q3rcon.Rcon, error) { func connectRcon(host string, port int, password string) (*q3rcon.Rcon, func(), error) {
rcon, err := q3rcon.New(host, port, password) client, err := q3rcon.New(host, port, password, q3rcon.WithTimeouts(map[string]time.Duration{
"map": time.Second,
"map_rotate": time.Second,
"map_restart": time.Second,
}))
if err != nil { if err != nil {
return nil, err return nil, nil, err
} }
return rcon, nil
closer := func() {
if err := client.Close(); err != nil {
log.Error(err)
}
}
return client, closer, nil
} }
// runCommands runs the commands given in the flag.Args slice. // runCommands runs the commands given in the flag.Args slice.
// If no commands are given, it defaults to running the "status" command. // If no commands are given, it defaults to running the "status" command.
func runCommands(commands []string, rcon *q3rcon.Rcon) { func runCommands(client *q3rcon.Rcon, commands []string) {
if len(commands) == 0 {
commands = append(commands, "status")
}
for _, cmd := range commands { for _, cmd := range commands {
resp, err := rcon.Send(cmd) resp, err := client.Send(cmd)
if err != nil { if err != nil {
log.Error(err) log.Error(err)
continue continue
@@ -100,7 +143,7 @@ func runCommands(commands []string, rcon *q3rcon.Rcon) {
} }
// interactiveMode continuously reads from input until a quit signal is given. // interactiveMode continuously reads from input until a quit signal is given.
func interactiveMode(rcon *q3rcon.Rcon, input io.Reader) error { func interactiveMode(client *q3rcon.Rcon, input io.Reader) error {
scanner := bufio.NewScanner(input) scanner := bufio.NewScanner(input)
for scanner.Scan() { for scanner.Scan() {
cmd := scanner.Text() cmd := scanner.Text()
@@ -108,7 +151,7 @@ func interactiveMode(rcon *q3rcon.Rcon, input io.Reader) error {
return nil return nil
} }
resp, err := rcon.Send(cmd) resp, err := client.Send(cmd)
if err != nil { if err != nil {
log.Error(err) log.Error(err)
continue continue

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.4 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 10 KiB

View File

@@ -5,24 +5,26 @@ BIN_DIR := bin
WINDOWS=$(BIN_DIR)/$(PROGRAM)_windows_amd64.exe WINDOWS=$(BIN_DIR)/$(PROGRAM)_windows_amd64.exe
LINUX=$(BIN_DIR)/$(PROGRAM)_linux_amd64 LINUX=$(BIN_DIR)/$(PROGRAM)_linux_amd64
MACOS=$(BIN_DIR)/$(PROGRAM)_darwin_amd64
VERSION=$(shell git log -n 1 --format=%h) VERSION=$(shell git log -n 1 --format=%h)
.DEFAULT_GOAL := build .DEFAULT_GOAL := build
.PHONY: fmt vet build windows linux test clean .PHONY: fmt vet build windows linux macos test clean
fmt: fmt:
$(GO) fmt ./... $(GO) fmt ./...
vet: fmt vet: fmt
$(GO) vet ./... $(GO) vet ./...
build: vet windows linux | $(BIN_DIR) build: vet windows linux macos | $(BIN_DIR)
@echo version: $(VERSION) @echo version: $(VERSION)
windows: $(WINDOWS) windows: $(WINDOWS)
linux: $(LINUX) linux: $(LINUX)
macos: $(MACOS)
$(WINDOWS): $(WINDOWS):
env GOOS=windows GOARCH=amd64 go build -v -o $(WINDOWS) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/$(PROGRAM)/ env GOOS=windows GOARCH=amd64 go build -v -o $(WINDOWS) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/$(PROGRAM)/
@@ -30,6 +32,9 @@ $(WINDOWS):
$(LINUX): $(LINUX):
env GOOS=linux GOARCH=amd64 go build -v -o $(LINUX) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/$(PROGRAM)/ env GOOS=linux GOARCH=amd64 go build -v -o $(LINUX) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/$(PROGRAM)/
$(MACOS):
env GOOS=darwin GOARCH=amd64 go build -v -o $(MACOS) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/$(PROGRAM)/
test: test:
$(GO) test ./... $(GO) test ./...

View File

@@ -140,6 +140,6 @@ func (r Rcon) listen(timeout time.Duration, respChan chan<- string, errChan chan
} }
} }
func (r Rcon) Close() { func (r Rcon) Close() error {
r.conn.Close() return r.conn.Close()
} }