Skip to content

About

Development kit for Golang. 服务于Golang的开发工具包

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Latest commit

 

History

18 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

suit-kit-golang

Build License Go Version Go Report Card

English | 中文说明

Overview

suit-kit-golang is a Go utility library providing reusable infrastructure components to help developers build high-quality applications quickly.

Features

  • Event Bus - Generic publish-subscribe event system with conditional filtering
  • Time Wheel Scheduler - High-performance timer for delayed and absolute-time tasks
  • Structured Logging - Zap-based logging with file rotation support
  • Lifecycle Management - Unified Init/Start/Stop interfaces for components
  • Signal Handling - Graceful OS signal handling with context cancellation
  • Network Utilities - IP address discovery, pattern matching, and random port listening
  • Collections - Thread-safe generic HashSet
  • Encoding Helpers - YAML configuration file loading

Requirements

  • Go 1.18+ (generics support required)

Installation

go get github.com/meshware/suit-kit-golang

Quick Start

Event Bus

package main

import (
    "context"
    "fmt"
    "time"

    "github.com/meshware/suit-kit-golang/pkg/event"
)

// Define an event
type MyEvent struct {
    event.AbstractEvent
    Data string
}

// Define an event handler
type MyHandler struct{}

func (h *MyHandler) Handler(event MyEvent) {
    fmt.Printf("Received: %s\n", event.Data)
}

func main() {
    // Create event bus
    bus := event.NewGoEventBus[MyEvent]()
    
    // Get publisher
    publisher := bus.GetPublisher("app.events", "default")
    publisher.Start(context.Background())
    defer publisher.Stop(context.Background())
    
    // Add handler
    publisher.AddHandler(&MyHandler{})
    
    // Publish event
    publisher.Offer(MyEvent{
        AbstractEvent: event.AbstractEvent{Source: "main"},
        Data: "Hello, Event Bus!",
    })
    
    time.Sleep(time.Second)
}

Time Wheel Scheduler

package main

import (
    "fmt"
    "time"

    "github.com/meshware/suit-kit-golang/pkg/task"
)

func main() {
    // Create scheduler: prefix, tickMs, slots, workerThreads
    scheduler := task.NewTimeScheduler("my-timer", 100, 60, 2)
    scheduler.Start()
    defer scheduler.Close()
    
    // Delay task (relative time)
    scheduler.Delay("task1", 500, func() {
        fmt.Println("Task1 executed at", time.Now())
    })
    
    // Absolute time task
    absTime := time.Now().UnixMilli() + 2000
    scheduler.Add("task2", absTime, func() {
        fmt.Println("Task2 executed at", time.Now())
    })
    
    // Cancellable task
    timeout := scheduler.Delay("task3", 5000, func() {
        fmt.Println("This won't execute")
    })
    timeout.Cancel()
    
    time.Sleep(3 * time.Second)
}

Structured Logging

package main

import (
    "github.com/meshware/suit-kit-golang/pkg/log"
    "go.uber.org/zap"
)

func main() {
    // Initialize from viper config
    log.InitLog()
    
    // Or create manually
    logger := log.New(nil, log.InfoLevel)
    log.ReplaceDefault(logger)
    
    // Use logger
    log.Info("Application started")
    log.Infof("Server listening on port %d", 8080)
    log.With(zap.String("key", "value")).Info("With fields")
    
    // Dynamic log level adjustment
    log.SetLevel(log.DebugLevel)
}

Thread-Safe Collections

package main

import (
    "fmt"
    "github.com/meshware/suit-kit-golang/pkg/collection"
)

func main() {
    // Create generic set
    set := collection.NewSet[string]()
    
    // Thread-safe operations
    set.Add("apple", "banana", "cherry")
    set.Add("apple") // Duplicate ignored
    
    fmt.Println("Size:", set.Size())              // 3
    fmt.Println("Contains:", set.Contains("banana")) // true
    
    // Iterate
    for _, v := range set.Values() {
        fmt.Println(v)
    }
}

Signal Handling

package main

import (
    "fmt"

    "github.com/meshware/suit-kit-golang/pkg/signals"
)

func main() {
    // Create context with signal handling (cancels on SIGTERM/SIGINT)
    ctx := signals.NewContext()
    
    fmt.Println("Press Ctrl+C to exit...")
    
    <-ctx.Done()
    fmt.Println("Received shutdown signal, gracefully exiting...")
}

Network Utilities

package main

import (
    "fmt"
    "github.com/meshware/suit-kit-golang/pkg/network"
)

func main() {
    // Get local IP (prefers private addresses)
    ip, err := network.GetLocalIP()
    if err == nil {
        fmt.Println("Local IP:", ip)
    }
    
    // IP pattern matching
    fmt.Println(network.MatchIP("192.168.1.*", "192.168.1.100", "8080")) // true
    fmt.Println(network.MatchIP("10.0.0.0/8", "10.1.2.3", ""))          // true
    fmt.Println(network.MatchIP("192.168.1.1-100", "192.168.1.50", ""))  // true
    
    // Listen on random port
    listener, _ := network.ListenOnTCPRandomPort("127.0.0.1")
    if listener != nil {
        fmt.Println("Listening on:", listener.Addr())
        listener.Close()
    }
}

YAML Configuration Loading

package main

import (
    "fmt"
    "github.com/meshware/suit-kit-golang/pkg/encoding/yaml"
)

type Config struct {
    Server struct {
        Port int    `yaml:"port"`
        Host string `yaml:"host"`
    } `yaml:"server"`
}

func main() {
    var config Config
    _, err := yaml.UnmarshalYMLConfig("config.yml", &config)
    if err != nil {
        fmt.Println("Failed to load config:", err)
        return
    }
    fmt.Printf("Server: %s:%d\n", config.Server.Host, config.Server.Port)
}

Package Structure

pkg/
├── collection/   # Collection data structures
│   └── hashset.go      # Thread-safe generic HashSet
├── encoding/     # Encoding helpers
│   ├── json/     # JSON utilities (placeholder)
│   └── yaml/     # YAML config loading
├── event/        # Event bus system
│   ├── event.go          # Event interface
│   ├── event_bus.go      # EventBus factory
│   ├── publisher.go      # Publisher implementation
│   ├── dispatcher.go     # Message queue dispatcher
│   ├── event_handler.go  # Handler interfaces
│   └── message.go        # Message wrapper
├── lifecycle/    # Lifecycle interfaces
│   ├── init.go   # Init interface
│   ├── start.go  # Start interface
│   ├── stop.go   # Stop interface
│   └── full.go   # Full (Init+Start+Stop) interface
├── log/          # Structured logging
│   ├── log.go    # Logger implementation
│   ├── rotate.go # File rotation config
│   ├── tee.go    # Multi-output logging
│   └── option.go # Log options
├── network/      # Network utilities
│   └── net.go    # IP handling and matching
├── signals/      # OS signal handling
│   ├── signal.go         # Signal handling core
│   ├── signal_posix.go   # POSIX signals
│   └── signal_windows.go # Windows signals
├── task/         # Time wheel scheduler
│   └── time_task.go      # TimeScheduler implementation
└── utils/        # Utility functions
    └── string.go         # String utilities

Dependencies

Dependency Version Purpose
go.uber.org/zap v1.27.0 High-performance structured logging
github.com/spf13/viper v1.19.0 Configuration management
gopkg.in/natefinsh/lumberjack.v2 v2.2.1 Size-based log rotation
github.com/lestrrat-go/file-rotatelogs v2.4.0 Time-based log rotation
github.com/pkg/errors v0.9.1 Error wrapping with stack traces

Development

Build

go build ./...

Test

# Run all tests
go test ./...

# Run tests for a specific package
go test ./pkg/event/...

# Run a single test
go test -run TestPublisher ./pkg/event/

# Run tests with race detector
go test -race ./...

# Verbose output
go test -v ./...

# Test coverage
go test -cover ./...

Lint

go vet ./...

License

suit-kit-golang is licensed under the Apache License 2.0.

Contributing

Issues and Pull Requests are welcome!

About

Development kit for Golang. 服务于Golang的开发工具包

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages