Elysia Tools

Browse tools, examples, visual explainers, and topic guides from one clear workspace.

Top Categories

Hubs

Language
ZHDERUPTENFRES

Elysia Tools

Navigation

Go

Web Mobile Features Go Samples

Web Go mobile-specific features examples including device information, network status, and vibration

Samples

Entries inside this sample collection

CodegoSimple

Device Information

Get device model, OS version, and other device properties

Difficulty

6/10

Estimated time

25 min

Tags

go, web, mobile features

Prerequisites

Intermediate Go, os/exec, runtime

go
// Web Go Device Information Examples
// Get device information using system calls and environment variables

package main

import (
	"fmt"
	"os"
	"os/exec"
	"runtime"
	"strings"
)

// 1. Basic Device Information

// DeviceInfo holds basic device information
type DeviceInfo struct {
	OS           string
	Architecture string
	Hostname     string
	CPUCount     int
	GoVersion    string
}

// GetDeviceInfo gets basic device information
func GetDeviceInfo() DeviceInfo {
	hostname, _ := os.Hostname()

	return DeviceInfo{
		OS:           runtime.GOOS,
		Architecture: runtime.GOARCH,
		Hostname:     hostname,
		CPUCount:     runtime.NumCPU(),
		GoVersion:    runtime.Version(),
	}
}

// PrintDeviceInfo prints device information
func PrintDeviceInfo(info DeviceInfo) {
	fmt.Println("=== Device Information ===")
	fmt.Printf("OS: %s\n", info.OS)
	fmt.Printf("Architecture: %s\n", info.Architecture)
	fmt.Printf("Hostname: %s\n", info.Hostname)
	fmt.Printf("CPU Count: %d\n", info.CPUCount)
	fmt.Printf("Go Version: %s\n", info.GoVersion)
}

// 2. OS-Specific Information

// GetOSVersion gets OS version (platform-specific)
func GetOSVersion() string {
	switch runtime.GOOS {
	case "windows":
		return getWindowsVersion()
	case "darwin":
		return getMacOSVersion()
	case "linux":
		return getLinuxVersion()
	default:
		return "Unknown OS"
	}
}

func getWindowsVersion() string {
	cmd := exec.Command("cmd", "ver")
	output, err := cmd.Output()
	if err != nil {
		return "Windows (version unknown)"
	}
	return strings.TrimSpace(string(output))
}

func getMacOSVersion() string {
	cmd := exec.Command("sw_vers", "-productVersion")
	output, err := cmd.Output()
	if err != nil {
		return "macOS (version unknown)"
	}
	return fmt.Sprintf("macOS %s", strings.TrimSpace(string(output)))
}

func getLinuxVersion() string {
	// Try /etc/os-release first
	cmd := exec.Command("sh", "-c", "cat /etc/os-release | grep PRETTY_NAME")
	output, err := cmd.Output()
	if err == nil {
		str := string(output)
		if strings.Contains(str, "PRETTY_NAME=") {
			parts := strings.Split(str, "=")
			if len(parts) > 1 {
				return strings.Trim(parts[1], ""\n")
			}
		}
	}

	// Fallback to uname
	cmd = exec.Command("uname", "-r")
	output, err = cmd.Output()
	if err != nil {
		return "Linux (version unknown)"
	}

	return fmt.Sprintf("Linux %s", strings.TrimSpace(string(output)))
}

// 3. Hardware Information

// MemoryInfo holds memory information
type MemoryInfo struct {
	Total     uint64
	Available uint64
	Used      uint64
	UsedPercent float64
}

// GetMemoryInfo gets memory information (platform-specific)
func GetMemoryInfo() MemoryInfo {
	switch runtime.GOOS {
	case "windows":
		return getWindowsMemoryInfo()
	case "darwin", "linux":
		return getUnixMemoryInfo()
	default:
		return MemoryInfo{}
	}
}

func getWindowsMemoryInfo() MemoryInfo {
	// Use wmic or GetPerformanceInfo
	cmd := exec.Command("wmic", "OS", "get", "TotalVisibleMemorySize,FreePhysicalMemory")
	output, err := cmd.Output()
	if err != nil {
		return MemoryInfo{}
	}

	// Parse output (simplified)
	lines := strings.Split(string(output), "\n")
	if len(lines) < 2 {
		return MemoryInfo{}
	}

	fields := strings.Fields(lines[1])
	if len(fields) < 2 {
		return MemoryInfo{}
	}

	// Values are in KB
	var total, available uint64
	fmt.Sscanf(fields[0], "%d", &total)
	fmt.Sscanf(fields[1], "%d", &available)

	total *= 1024        // Convert to bytes
	available *= 1024
	used := total - available

	return MemoryInfo{
		Total:     total,
		Available: available,
		Used:      used,
		UsedPercent: float64(used) / float64(total) * 100,
	}
}

func getUnixMemoryInfo() MemoryInfo {
	// Read from /proc/meminfo on Linux
	cmd := exec.Command("sh", "-c", "cat /proc/meminfo | grep -E 'MemTotal|MemAvailable'")
	output, err := cmd.Output()
	if err != nil {
		return MemoryInfo{}
	}

	lines := strings.Split(string(output), "\n")
	var total, available uint64

	for _, line := range lines {
		fields := strings.Fields(line)
		if len(fields) >= 2 {
			var value uint64
			fmt.Sscanf(fields[1], "%d", &value)
			value *= 1024 // Convert to bytes

			if strings.Contains(line, "MemTotal") {
				total = value
			} else if strings.Contains(line, "MemAvailable") {
				available = value
			}
		}
	}

	if total == 0 {
		return MemoryInfo{}
	}

	used := total - available

	return MemoryInfo{
		Total:     total,
		Available: available,
		Used:      used,
		UsedPercent: float64(used) / float64(total) * 100,
	}
}

// FormatMemorySize formats memory size in human-readable format
func FormatMemorySize(bytes uint64) string {
	const (
		KB = 1024
		MB = KB * 1024
		GB = MB * 1024
	)

	switch {
	case bytes >= GB:
		return fmt.Sprintf("%.2f GB", float64(bytes)/float64(GB))
	case bytes >= MB:
		return fmt.Sprintf("%.2f MB", float64(bytes)/float64(MB))
	case bytes >= KB:
		return fmt.Sprintf("%.2f KB", float64(bytes)/float64(KB))
	default:
		return fmt.Sprintf("%d B", bytes)
	}
}

// CPUInfo holds CPU information
type CPUInfo struct {
	Model     string
	Cores     int
	Frequency string
}

// GetCPUInfo gets CPU information
func GetCPUInfo() CPUInfo {
	info := CPUInfo{
		Cores: runtime.NumCPU(),
	}

	switch runtime.GOOS {
	case "windows":
		info.Model = getWindowsCPUModel()
	case "darwin":
		info.Model = getMacOSCPUModel()
	case "linux":
		info.Model = getLinuxCPUModel()
	}

	return info
}

func getWindowsCPUModel() string {
	cmd := exec.Command("wmic", "cpu", "get", "name")
	output, err := cmd.Output()
	if err != nil {
		return "Unknown CPU"
	}
	lines := strings.Split(string(output), "\n")
	if len(lines) > 1 {
		return strings.TrimSpace(lines[1])
	}
	return "Unknown CPU"
}

func getMacOSCPUModel() string {
	cmd := exec.Command("sysctl", "-n", "machdep.cpu.brand_string")
	output, err := cmd.Output()
	if err != nil {
		return "Unknown CPU"
	}
	return strings.TrimSpace(string(output))
}

func getLinuxCPUModel() string {
	cmd := exec.Command("sh", "-c", "cat /proc/cpuinfo | grep 'model name' | head -1")
	output, err := cmd.Output()
	if err != nil {
		return "Unknown CPU"
	}

	str := string(output)
	parts := strings.Split(str, ":")
	if len(parts) > 1 {
		return strings.TrimSpace(parts[1])
	}

	return "Unknown CPU"
}

// 4. Screen Information

// ScreenInfo holds screen/display information
type ScreenInfo struct {
	Width       int
	Height      int
	DPI         int
	Orientation string
}

// GetScreenInfo gets screen information
func GetScreenInfo() ScreenInfo {
	// This is platform-dependent and may require external libraries
	// For web applications, you'd use JavaScript's window.screen

	// Simulated values for demonstration
	return ScreenInfo{
		Width:       1920,
		Height:      1080,
		DPI:         96,
		Orientation: "landscape",
	}
}

// 5. Battery Information

// BatteryInfo holds battery information
type BatteryInfo struct {
	Level     int
	Charging  bool
	TimeRemaining string
}

// GetBatteryInfo gets battery information (platform-specific)
func GetBatteryInfo() BatteryInfo {
	switch runtime.GOOS {
	case "darwin":
		return getMacOSBatteryInfo()
	case "linux":
		return getLinuxBatteryInfo()
	default:
		return BatteryInfo{}
	}
}

func getMacOSBatteryInfo() BatteryInfo {
	cmd := exec.Command("pmset", "-g", "batt")
	output, err := cmd.Output()
	if err != nil {
		return BatteryInfo{}
	}

	str := string(output)
	info := BatteryInfo{}

	// Parse battery percentage
	if strings.Contains(str, "%") {
		parts := strings.Fields(str)
		for _, part := range parts {
			if strings.Contains(part, "%") {
				var percent int
				fmt.Sscanf(part, "%d", &percent)
				info.Level = percent
			}
		}
	}

	// Check if charging
	info.Charging = strings.Contains(str, "AC Power")

	return info
}

func getLinuxBatteryInfo() BatteryInfo {
	// Read from /sys/class/power_supply/BAT0/
	cmd := exec.Command("sh", "-c", "cat /sys/class/power_supply/BAT0/capacity")
	output, err := cmd.Output()
	if err != nil {
		return BatteryInfo{}
	}

	var level int
	fmt.Sscanf(strings.TrimSpace(string(output)), "%d", &level)

	cmd = exec.Command("sh", "-c", "cat /sys/class/power_supply/BAT0/status")
	statusOutput, _ := cmd.Output()

	return BatteryInfo{
		Level:    level,
		Charging: strings.Contains(string(statusOutput), "Charging"),
	}
}

// 6. Application Information

// AppInfo holds application information
type AppInfo struct {
	Name      string
	Version   string
	Build     string
	BuildDate string
	Author    string
}

// GetAppInfo gets application information
func GetAppInfo() AppInfo {
	// These would typically come from build flags or config
	return AppInfo{
		Name:      "My Go App",
		Version:   "1.0.0",
		Build:     "12345",
		BuildDate: "2025-12-30",
		Author:    "Your Name",
	}
}

// 7. Environment Information

// EnvironmentInfo holds environment information
type EnvironmentInfo struct {
	Variables map[string]string
	Path      string
	Home      string
	Terminal  string
}

// GetEnvironmentInfo gets environment information
func GetEnvironmentInfo() EnvironmentInfo {
	return EnvironmentInfo{
		Variables: getSelectedEnvVars(),
		Path:      os.Getenv("PATH"),
		Home:      os.Getenv("HOME"),
		Terminal:  os.Getenv("TERM"),
	}
}

func getSelectedEnvVars() map[string]string {
	selected := []string{
		"PATH", "HOME", "USER", "SHELL",
		"APPDATA", "PROGRAMFILES", "TEMP",
		"LANG", "LC_ALL",
	}

	result := make(map[string]string)
	for _, key := range selected {
		if value := os.Getenv(key); value != "" {
			result[key] = value
		}
	}

	return result
}

// 8. Device Identification

// DeviceID generates a unique device ID
func GetDeviceID() string {
	hostname, _ := os.Hostname()
	os := runtime.GOOS
	arch := runtime.GOARCH

	// Create a simple ID from available info
	return fmt.Sprintf("%s-%s-%s", hostname, os, arch)
}

// GetFingerprint creates device fingerprint
func GetDeviceFingerprint() string {
	info := GetDeviceInfo()
	cpuInfo := GetCPUInfo()

	return fmt.Sprintf("%s-%s-%d-%s",
		info.OS,
		info.Architecture,
		info.CPUCount,
		cpuInfo.Model,
	)
}

// Usage Examples
func main() {
	fmt.Println("=== Web Go Device Information Examples ===\n")

	// 1. Basic device info
	fmt.Println("--- 1. Basic Device Info ---")
	deviceInfo := GetDeviceInfo()
	PrintDeviceInfo(deviceInfo)

	// 2. OS version
	fmt.Println("\n--- 2. OS Version ---")
	osVersion := GetOSVersion()
	fmt.Printf("OS Version: %s\n", osVersion)

	// 3. CPU info
	fmt.Println("\n--- 3. CPU Information ---")
	cpuInfo := GetCPUInfo()
	fmt.Printf("CPU Model: %s\n", cpuInfo.Model)
	fmt.Printf("CPU Cores: %d\n", cpuInfo.Cores)

	// 4. Memory info
	fmt.Println("\n--- 4. Memory Information ---")
	memInfo := GetMemoryInfo()
	fmt.Printf("Total Memory: %s\n", FormatMemorySize(memInfo.Total))
	fmt.Printf("Available: %s\n", FormatMemorySize(memInfo.Available))
	fmt.Printf("Used: %s (%.1f%%)\n",
		FormatMemorySize(memInfo.Used),
		memInfo.UsedPercent)

	// 5. Screen info
	fmt.Println("\n--- 5. Screen Information ---")
	screenInfo := GetScreenInfo()
	fmt.Printf("Resolution: %dx%d\n", screenInfo.Width, screenInfo.Height)
	fmt.Printf("DPI: %d\n", screenInfo.DPI)
	fmt.Printf("Orientation: %s\n", screenInfo.Orientation)

	// 6. Battery info
	fmt.Println("\n--- 6. Battery Information ---")
	batteryInfo := GetBatteryInfo()
	if batteryInfo.Level > 0 {
		fmt.Printf("Battery Level: %d%%\n", batteryInfo.Level)
		fmt.Printf("Charging: %v\n", batteryInfo.Charging)
	} else {
		fmt.Println("Battery information not available")
	}

	// 7. App info
	fmt.Println("\n--- 7. Application Information ---")
	appInfo := GetAppInfo()
	fmt.Printf("App: %s v%s\n", appInfo.Name, appInfo.Version)
	fmt.Printf("Build: %s (%s)\n", appInfo.Build, appInfo.BuildDate)

	// 8. Device ID
	fmt.Println("\n--- 8. Device Identification ---")
	deviceID := GetDeviceID()
	fmt.Printf("Device ID: %s\n", deviceID)

	fingerprint := GetDeviceFingerprint()
	fmt.Printf("Fingerprint: %s\n", fingerprint)

	// 9. Environment
	fmt.Println("\n--- 9. Environment ---")
	envInfo := GetEnvironmentInfo()
	fmt.Printf("Home: %s\n", envInfo.Home)
	fmt.Printf("Terminal: %s\n", envInfo.Terminal)

	fmt.Println("\n=== All Device Information Examples Completed ===")
}
CodegoSimple

Network Status

Check network connection status and type

Difficulty

6/10

Estimated time

30 min

Tags

go, web, mobile features

Prerequisites

Intermediate Go, net package, os/exec

go
// Web Go Network Status Examples
// Check network connection status and type

package main

import (
	"fmt"
	"net"
	"os/exec"
	"runtime"
	"strings"
	"time"
)

// 1. Basic Network Status

// NetworkStatus holds network status information
type NetworkStatus struct {
	Connected   bool
	Type        string
	IP          string
	Gateway     string
	DNS         []string
	Latency     time.Duration
}

// GetNetworkStatus gets current network status
func GetNetworkStatus() NetworkStatus {
	status := NetworkStatus{
		Connected: false,
		Type:      "Unknown",
		DNS:       []string{},
	}

	// Check connectivity
	if isNetworkAvailable() {
		status.Connected = true
		status.Type = detectNetworkType()
		status.IP = getLocalIP()
		status.Gateway = getDefaultGateway()
		status.DNS = getDNSServers()
		status.Latency = measureLatency()
	}

	return status
}

// isNetworkAvailable checks if network is available
func isNetworkAvailable() bool {
	// Try to connect to a well-known server
	_, err := net.DialTimeout("tcp", "8.8.8.8:53", 2*time.Second)
	return err == nil
}

// detectNetworkType detects network connection type
func detectNetworkType() string {
	// This is platform-specific
	switch runtime.GOOS {
	case "darwin":
		return detectMacOSNetworkType()
	case "linux":
		return detectLinuxNetworkType()
	case "windows":
		return detectWindowsNetworkType()
	default:
		return "Ethernet"
	}
}

func detectMacOSNetworkType() string {
	cmd := exec.Command("networksetup", "-listallnetworkservices")
	output, _ := cmd.Output()

	str := string(output)
	if strings.Contains(str, "Wi-Fi") || strings.Contains(str, "AirPort") {
		return "Wi-Fi"
	}

	return "Ethernet"
}

func detectLinuxNetworkType() string {
	// Check wireless interfaces
	cmd := exec.Command("ls", "/sys/class/net")
	output, _ := cmd.Output()

	interfaces := strings.Split(string(output), "\n")
	for _, iface := range interfaces {
		if strings.HasPrefix(iface, "w") || strings.HasPrefix(iface, "wlan") {
			return "Wi-Fi"
		}
	}

	return "Ethernet"
}

func detectWindowsNetworkType() string {
	cmd := exec.Command("netsh", "interface", "show", "interface")
	output, _ := cmd.Output()

	str := string(output)
	if strings.Contains(str, "Wi-Fi") || strings.Contains(str, "Wireless") {
		return "Wi-Fi"
	}

	return "Ethernet"
}

// getLocalIP gets local IP address
func getLocalIP() string {
	conn, err := net.Dial("udp", "8.8.8.8:80")
	if err != nil {
		return "Unknown"
	}
	defer conn.Close()

	localAddr := conn.LocalAddr().(*net.UDPAddr)
	return localAddr.IP.String()
}

// getDefaultGateway gets default gateway
func getDefaultGateway() string {
	switch runtime.GOOS {
	case "darwin":
		cmd := exec.Command("netstat", "-nr")
		output, _ := cmd.Output()
		lines := strings.Split(string(output), "\n")
		for _, line := range lines {
			if strings.Contains(line, "default") {
				fields := strings.Fields(line)
				if len(fields) > 1 {
					return fields[1]
				}
			}
		}
	case "linux":
		cmd := exec.Command("ip", "route")
		output, _ := cmd.Output()
		lines := strings.Split(string(output), "\n")
		for _, line := range lines {
			if strings.HasPrefix(line, "default") {
				fields := strings.Fields(line)
				if len(fields) > 2 {
					return fields[2]
				}
			}
		}
	case "windows":
		cmd := exec.Command("route", "print", "0.0.0.0")
		output, _ := cmd.Output()
		lines := strings.Split(string(output), "\n")
		for _, line := range lines {
			if strings.Contains(line, "0.0.0.0") {
				fields := strings.Fields(line)
				if len(fields) > 2 {
					return fields[2]
				}
			}
		}
	}

	return "Unknown"
}

// getDNSServers gets DNS servers
func getDNSServers() []string {
	var dns []string

	switch runtime.GOOS {
	case "darwin":
		cmd := exec.Command("scutil", "--dns")
		output, _ := cmd.Output()
		lines := strings.Split(string(output), "\n")
		for _, line := range lines {
			if strings.Contains(line, "nameserver") {
				fields := strings.Fields(line)
				if len(fields) > 1 {
					dns = append(dns, fields[1])
				}
			}
		}
	case "linux":
		cmd := exec.Command("cat", "/etc/resolv.conf")
		output, _ := cmd.Output()
		lines := strings.Split(string(output), "\n")
		for _, line := range lines {
			if strings.HasPrefix(line, "nameserver") {
				fields := strings.Fields(line)
				if len(fields) > 1 {
					dns = append(dns, fields[1])
				}
			}
		}
	case "windows":
		cmd := exec.Command("nslookup", "localhost")
		output, _ := cmd.Output()
		lines := strings.Split(string(output), "\n")
		for _, line := range lines {
			if strings.Contains(line, "Server:") {
				fields := strings.Fields(line)
				if len(fields) > 1 {
					dns = append(dns, fields[1])
				}
			}
		}
	}

	return dns
}

// measureLatency measures network latency
func measureLatency() time.Duration {
	start := time.Now()

	conn, err := net.DialTimeout("tcp", "8.8.8.8:53", 5*time.Second)
	if err != nil {
		return 0
	}
	defer conn.Close()

	return time.Since(start)
}

// 2. Network Speed Test

// SpeedTestResult holds speed test results
type SpeedTestResult struct {
	DownloadSpeed float64 // Mbps
	UploadSpeed   float64 // Mbps
	Ping          time.Duration
}

// RunSpeedTest runs network speed test
func RunSpeedTest() SpeedTestResult {
	// Ping test
	ping := measureLatency()

	// Download speed (simplified - just measures time to download small file)
	downloadSpeed := measureDownloadSpeed()

	// Upload speed (simplified)
	uploadSpeed := measureUploadSpeed()

	return SpeedTestResult{
		DownloadSpeed: downloadSpeed,
		UploadSpeed:   uploadSpeed,
		Ping:          ping,
	}
}

func measureDownloadSpeed() float64 {
	// Simplified download speed test
	start := time.Now()

	// Download small test file
	// In real implementation, you'd download a larger file
	conn, err := net.DialTimeout("tcp", "example.com:80", 5*time.Second)
	if err != nil {
		return 0
	}
	defer conn.Close()

	elapsed := time.Since(start).Seconds()
	if elapsed == 0 {
		return 0
	}

	// Rough estimate (assuming ~1MB transfer)
	sizeMB := 1.0
	return sizeMB / elapsed
}

func measureUploadSpeed() float64 {
	// Simplified upload speed test
	start := time.Now()

	conn, err := net.DialTimeout("tcp", "example.com:80", 5*time.Second)
	if err != nil {
		return 0
	}
	defer conn.Close()

	// Write some data
	data := make([]byte, 1024*1024) // 1MB
	conn.Write(data)

	elapsed := time.Since(start).Seconds()
	if elapsed == 0 {
		return 0
	}

	sizeMB := 1.0
	return sizeMB / elapsed
}

// 3. Network Interface Information

// NetworkInterface holds interface information
type NetworkInterface struct {
	Name      string
	IP        string
	Netmask   string
	MAC       string
	Up        bool
	Type      string
}

// GetNetworkInterfaces gets all network interfaces
func GetNetworkInterfaces() []NetworkInterface {
	var interfaces []NetworkInterface

	ifaces, _ := net.Interfaces()

	for _, iface := range ifaces {
		addrs, _ := iface.Addrs()
		var ip string

		for _, addr := range addrs {
			if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
				if ipnet.IP.To4() != nil {
					ip = ipnet.IP.String()
					break
				}
			}
		}

		ni := NetworkInterface{
			Name:    iface.Name,
			IP:      ip,
			MAC:     iface.HardwareAddr.String(),
			Up:      iface.Flags&net.FlagUp != 0,
		}

		// Detect interface type
		if strings.Contains(iface.Name, "w") || strings.Contains(iface.Name, "Wi-Fi") {
			ni.Type = "Wi-Fi"
		} else if strings.Contains(iface.Name, "eth") || strings.Contains(iface.Name, "en") {
			ni.Type = "Ethernet"
		} else {
			ni.Type = "Other"
		}

		interfaces = append(interfaces, ni)
	}

	return interfaces
}

// 4. Network Monitoring

// NetworkMonitor monitors network changes
type NetworkMonitor struct {
	callback func(NetworkStatus)
	stopChan chan bool
}

// NewNetworkMonitor creates network monitor
func NewNetworkMonitor(callback func(NetworkStatus)) *NetworkMonitor {
	return &NetworkMonitor{
		callback: callback,
		stopChan: make(chan bool),
	}
}

// Start starts monitoring network changes
func (nm *NetworkMonitor) Start(interval time.Duration) {
	ticker := time.NewTicker(interval)
	lastStatus := GetNetworkStatus()

	go func() {
		for {
			select {
			case <-ticker.C:
				currentStatus := GetNetworkStatus()

				// Check for changes
				if currentStatus.Connected != lastStatus.Connected ||
					currentStatus.Type != lastStatus.Type {
					nm.callback(currentStatus)
					lastStatus = currentStatus
				}
			case <-nm.stopChan:
				ticker.Stop()
				return
			}
		}
	}()
}

// Stop stops monitoring
func (nm *NetworkMonitor) Stop() {
	nm.stopChan <- true
}

// 5. Connectivity Check

// CheckConnectivity checks connectivity to specific host
func CheckConnectivity(host string, port int, timeout time.Duration) bool {
	address := fmt.Sprintf("%s:%d", host, port)
	conn, err := net.DialTimeout("tcp", address, timeout)
	if err != nil {
		return false
	}
	conn.Close()
	return true
}

// CheckMultipleHosts checks connectivity to multiple hosts
func CheckMultipleHosts(hosts []string, timeout time.Duration) map[string]bool {
	results := make(map[string]bool)

	for _, host := range hosts {
		results[host] = CheckConnectivity(host, 80, timeout)
	}

	return results
}

// 6. Network Statistics

// NetworkStats holds network statistics
type NetworkStats struct {
	BytesSent     uint64
	BytesReceived uint64
	PacketsSent     uint64
	PacketsReceived uint64
}

// GetNetworkStats gets network statistics (platform-specific)
func GetNetworkStats() NetworkStats {
	// Platform-specific implementation
	// This would typically read from /proc/net/dev on Linux
	// or use performance counters on Windows

	return NetworkStats{}
}

// Usage Examples
func main() {
	fmt.Println("=== Web Go Network Status Examples ===\n")

	// 1. Network status
	fmt.Println("--- 1. Network Status ---")
	status := GetNetworkStatus()
	fmt.Printf("Connected: %v\n", status.Connected)
	fmt.Printf("Type: %s\n", status.Type)
	fmt.Printf("IP: %s\n", status.IP)
	fmt.Printf("Gateway: %s\n", status.Gateway)
	fmt.Printf("DNS: %v\n", status.DNS)
	fmt.Printf("Latency: %v\n", status.Latency)

	// 2. Network interfaces
	fmt.Println("\n--- 2. Network Interfaces ---")
	interfaces := GetNetworkInterfaces()
	for _, iface := range interfaces {
		if iface.Up && iface.IP != "" {
			fmt.Printf("Interface: %s (%s)\n", iface.Name, iface.Type)
			fmt.Printf("  IP: %s\n", iface.IP)
			fmt.Printf("  MAC: %s\n", iface.MAC)
		}
	}

	// 3. Speed test
	fmt.Println("\n--- 3. Speed Test ---")
	speedTest := RunSpeedTest()
	fmt.Printf("Download: %.2f Mbps\n", speedTest.DownloadSpeed)
	fmt.Printf("Upload: %.2f Mbps\n", speedTest.UploadSpeed)
	fmt.Printf("Ping: %v\n", speedTest.Ping)

	// 4. Connectivity check
	fmt.Println("\n--- 4. Connectivity Check ---")
	hosts := []string{"google.com", "github.com", "example.com"}
	results := CheckMultipleHosts(hosts, 2*time.Second)
	for host, connected := range results {
		status := "✓"
		if !connected {
			status = "✗"
		}
		fmt.Printf("%s %s: %v\n", status, host, connected)
	}

	// 5. Network monitoring
	fmt.Println("\n--- 5. Network Monitoring ---")
	monitor := NewNetworkMonitor(func(status NetworkStatus) {
		fmt.Printf("Network changed: Connected=%v, Type=%s\n",
			status.Connected, status.Type)
	})

	fmt.Println("Monitoring network for 10 seconds...")
	monitor.Start(2 * time.Second)
	time.Sleep(10 * time.Second)
	monitor.Stop()

	fmt.Println("\n=== All Network Status Examples Completed ===")
}
CodegoSimple

Vibration

Control device vibration (limited support, platform-specific)

Difficulty

5/10

Estimated time

20 min

Tags

go, web, mobile features

Prerequisites

Basic Go, time package

go
// Web Go Vibration Examples
// Control device vibration (platform-specific, limited support)

package main

import (
	"fmt"
	"os/exec"
	"runtime"
	"time"
)

// 1. Basic Vibration

// Vibrate vibrates the device for specified duration
func Vibrate(duration time.Duration) error {
	switch runtime.GOOS {
	case "darwin":
		return vibrateMacOS(duration)
	case "linux":
		return vibrateLinux(duration)
	case "windows":
		return vibrateWindows(duration)
	case "android":
		return vibrateAndroid(duration)
	default:
		return fmt.Errorf("vibration not supported on %s", runtime.GOOS)
	}
}

// vibrateMacOS vibrates on macOS (limited support)
func vibrateMacOS(duration time.Duration) error {
	// macOS has limited vibration support
	// Can use haptic feedback on trackpads or external devices
	cmd := exec.Command("osascript", "-e",
		`beep 1`)
	return cmd.Run()
}

// vibrateLinux vibrates on Linux
func vibrateLinux(duration time.Duration) error {
	// Check if vibration is available
	if !hasVibrationSupport() {
		return fmt.Errorf("vibration not available")
	}

	// Try using systemd-inhibit or other tools
	// This is highly distribution-specific
	cmd := exec.Command("notify-send", "-t",
		fmt.Sprintf("%d", duration.Milliseconds()),
		"Vibration", "Device vibrating")
	return cmd.Run()
}

// vibrateWindows vibrates on Windows
func vibrateWindows(duration time.Duration) error {
	// Windows doesn't have native vibration support
	// Could use Xbox controller vibration or external APIs
	return fmt.Errorf("vibration not supported on Windows")
}

// vibrateAndroid vibrates on Android
func vibrateAndroid(duration time.Duration) error {
	// Would use JNI to call Android Vibrator API
	// This requires Go Mobile or gomobile bindings
	cmd := exec.Command("sh", "-c",
		fmt.Sprintf("echo vibrate %d > /sys/class/timed_output/vibrator/enable",
			duration.Milliseconds()))
	return cmd.Run()
}

// hasVibrationSupport checks if vibration is available
func hasVibrationSupport() bool {
	// Check for vibration device
	_, err := exec.Command("ls", "/sys/class/timed_output/vibrator").Output()
	return err == nil
}

// 2. Vibration Patterns

// VibrationPattern defines a vibration pattern
type VibrationPattern struct {
	Durations []time.Duration
}

// NewVibrationPattern creates new vibration pattern
func NewVibrationPattern(durations ...time.Duration) VibrationPattern {
	return VibrationPattern{
		Durations: durations,
	}
}

// Play plays the vibration pattern
func (vp VibrationPattern) Play() error {
	for _, duration := range vp.Durations {
		if err := Vibrate(duration); err != nil {
			return err
		}
		time.Sleep(duration)
	}
	return nil
}

// Common vibration patterns
var (
	// PatternTap short tap vibration
	PatternTap = VibrationPattern{
		Durations: []time.Duration{50 * time.Millisecond},
	}

	// PatternDoubleTap double tap vibration
	PatternDoubleTap = VibrationPattern{
		Durations: []time.Duration{
			50 * time.Millisecond,
			100 * time.Millisecond,
			50 * time.Millisecond,
		},
	}

	// PatternSuccess success notification pattern
	PatternSuccess = VibrationPattern{
		Durations: []time.Duration{
			100 * time.Millisecond,
			50 * time.Millisecond,
			100 * time.Millisecond,
		},
	}

	// PatternError error notification pattern
	PatternError = VibrationPattern{
		Durations: []time.Duration{
			200 * time.Millisecond,
			100 * time.Millisecond,
			200 * time.Millisecond,
			100 * time.Millisecond,
			200 * time.Millisecond,
		},
	}

	// PatternNotification notification pattern
	PatternNotification = VibrationPattern{
		Durations: []time.Duration{
			100 * time.Millisecond,
			50 * time.Millisecond,
			100 * time.Millisecond,
			50 * time.Millisecond,
			100 * time.Millisecond,
		},
	}
)

// 3. Haptic Feedback

// HapticType defines type of haptic feedback
type HapticType int

const (
	HapticImpactLight HapticType = iota
	HapticImpactMedium
	HapticImpactHeavy
	HapticNotificationSuccess
	HapticNotificationWarning
	HapticNotificationError
	HapticSelection
)

// HapticFeedback performs haptic feedback
func HapticFeedback(feedbackType HapticType) error {
	switch feedbackType {
	case HapticImpactLight:
		return Vibrate(10 * time.Millisecond)
	case HapticImpactMedium:
		return Vibrate(25 * time.Millisecond)
	case HapticImpactHeavy:
		return Vibrate(50 * time.Millisecond)
	case HapticNotificationSuccess:
		return PatternSuccess.Play()
	case HapticNotificationWarning:
		return Vibrate(100 * time.Millisecond)
	case HapticNotificationError:
		return PatternError.Play()
	case HapticSelection:
		return Vibrate(15 * time.Millisecond)
	default:
		return fmt.Errorf("unknown haptic type")
	}
}

// 4. Vibration Manager

// VibrationManager manages vibration operations
type VibrationManager struct {
	enabled   bool
	intensity float64 // 0.0 to 1.0
	current   time.Duration
}

// NewVibrationManager creates vibration manager
func NewVibrationManager() *VibrationManager {
	return &VibrationManager{
		enabled:   true,
		intensity: 1.0,
	}
}

// SetEnabled enables or disables vibration
func (vm *VibrationManager) SetEnabled(enabled bool) {
	vm.enabled = enabled
}

// SetIntensity sets vibration intensity
func (vm *VibrationManager) SetIntensity(intensity float64) {
	vm.intensity = intensity
}

// Vibrate vibrates with manager settings
func (vm *VibrationManager) Vibrate(duration time.Duration) error {
	if !vm.enabled {
		return nil
	}

	// Adjust duration by intensity
	adjusted := time.Duration(float64(duration) * vm.intensity)
	return Vibrate(adjusted)
}

// VibratePattern vibrates pattern with manager settings
func (vm *VibrationManager) VibratePattern(pattern VibrationPattern) error {
	for _, duration := range pattern.Durations {
		if err := vm.Vibrate(duration); err != nil {
			return err
		}
		time.Sleep(duration)
	}
	return nil
}

// IsEnabled returns if vibration is enabled
func (vm *VibrationManager) IsEnabled() bool {
	return vm.enabled
}

// GetIntensity returns current intensity
func (vm *VibrationManager) GetIntensity() float64 {
	return vm.intensity
}

// 5. Vibration with Fallback

// VibrateWithFallback vibrates with visual fallback
func VibrateWithFallback(duration time.Duration, fallback func()) {
	if err := Vibrate(duration); err != nil {
		// Fallback to visual feedback
		if fallback != nil {
			fallback()
		}
	}
}

// 6. Feedback Combinations

// FeedbackType defines type of feedback
type FeedbackType int

const (
	VisualFeedback FeedbackType = iota
	HapticOnlyFeedback
	AudioFeedback
	CombinedFeedback
)

// Feedback provides combined feedback
func Feedback(feedbackType FeedbackType, message string) {
	switch feedbackType {
	case VisualFeedback:
		fmt.Printf("[VISUAL] %s\n", message)
	case HapticOnlyFeedback:
		PatternTap.Play()
	case AudioFeedback:
		// Play sound
		fmt.Printf("[AUDIO] %s\n", message)
	case CombinedFeedback:
		fmt.Printf("[COMBINED] %s\n", message)
		PatternTap.Play()
	}
}

// 7. Context-Aware Vibration

// VibrationContext defines vibration context
type VibrationContext struct {
	IsSilent   bool
	IsImportant bool
	UserPreference string
}

// ContextualVibrate vibrates based on context
func ContextualVibrate(context VibrationContext, pattern VibrationPattern) error {
	// Check if should vibrate
	if context.IsSilent && !context.IsImportant {
		return nil // Don't vibrate in silent mode unless important
	}

	// Respect user preference
	switch context.UserPreference {
	case "always":
		return pattern.Play()
	case "never":
		return nil
	case "important_only":
		if context.IsImportant {
			return pattern.Play()
		}
		return nil
	default:
		return pattern.Play()
	}
}

// 8. Vibration Scheduler

// VibrationScheduler schedules vibrations
type VibrationScheduler struct {
	queues []VibrationTask
}

// VibrationTask represents a scheduled vibration
type VibrationTask struct {
	Pattern VibrationPattern
	Delay   time.Duration
}

// NewVibrationScheduler creates vibration scheduler
func NewVibrationScheduler() *VibrationScheduler {
	return &VibrationScheduler{
		queues: []VibrationTask{},
	}
}

// Schedule schedules a vibration
func (vs *VibrationScheduler) Schedule(pattern VibrationPattern, delay time.Duration) {
	vs.queues = append(vs.queues, VibrationTask{
		Pattern: pattern,
		Delay:   delay,
	})
}

// Run executes scheduled vibrations
func (vs *VibrationScheduler) Run() {
	for _, task := range vs.queues {
		time.Sleep(task.Delay)
		task.Pattern.Play()
	}
	vs.queues = []VibrationTask{}
}

// Usage Examples
func main() {
	fmt.Println("=== Web Go Vibration Examples ===\n")

	// 1. Basic vibration
	fmt.Println("--- 1. Basic Vibration ---")
	err := Vibrate(100 * time.Millisecond)
	if err != nil {
		fmt.Printf("Vibration error: %v\n", err)
		fmt.Println("(Vibration may not be supported on this platform)")
	}

	// 2. Vibration patterns
	fmt.Println("\n--- 2. Vibration Patterns ---")
	fmt.Println("Playing tap pattern...")
	PatternTap.Play()

	time.Sleep(500 * time.Millisecond)

	fmt.Println("Playing double tap pattern...")
	PatternDoubleTap.Play()

	time.Sleep(500 * time.Millisecond)

	fmt.Println("Playing success pattern...")
	PatternSuccess.Play()

	// 3. Haptic feedback
	fmt.Println("\n--- 3. Haptic Feedback ---")
	HapticFeedback(HapticImpactLight)
	time.Sleep(200 * time.Millisecond)
	HapticFeedback(HapticImpactMedium)
	time.Sleep(200 * time.Millisecond)
	HapticFeedback(HapticImpactHeavy)

	// 4. Vibration manager
	fmt.Println("\n--- 4. Vibration Manager ---")
	manager := NewVibrationManager()
	manager.SetIntensity(0.5) // 50% intensity

	fmt.Printf("Vibration enabled: %v\n", manager.IsEnabled())
	fmt.Printf("Intensity: %.0f%%\n", manager.GetIntensity()*100)

	manager.Vibrate(200 * time.Millisecond)

	// 5. Context-aware vibration
	fmt.Println("\n--- 5. Context-Aware Vibration ---")
	context := VibrationContext{
		IsSilent:    false,
		IsImportant: true,
		UserPreference: "always",
	}

	ContextualVibrate(context, PatternNotification)

	// 6. Scheduled vibrations
	fmt.Println("\n--- 6. Scheduled Vibrations ---")
	scheduler := NewVibrationScheduler()
	scheduler.Schedule(PatternTap, 0)
	scheduler.Schedule(PatternDoubleTap, 500*time.Millisecond)
	scheduler.Schedule(PatternSuccess, 1000*time.Millisecond)

	go scheduler.Run()
	time.Sleep(2 * time.Second) // Wait for all vibrations

	// 7. Fallback
	fmt.Println("\n--- 7. Vibration with Fallback ---")
	VibrateWithFallback(100*time.Millisecond, func() {
		fmt.Println("[FALLBACK] Visual feedback instead of vibration")
	})

	// 8. Combined feedback
	fmt.Println("\n--- 8. Combined Feedback ---")
	Feedback(CombinedFeedback, "Operation successful")

	fmt.Println("\n=== All Vibration Examples Completed ===")
	fmt.Println("Note: Vibration support is platform-specific and limited")
	fmt.Println("For mobile development, use Go Mobile (gomobile) or platform-specific APIs")
}

Tools

Tools frequently paired with this sample

Related

Related sample collections

Related

Related workflows

Hub

Infer JSON Schema from Samples and Spreadsheets

Derive a reviewable JSON Schema draft from representative JSON samples or XLSX rows, then inspect types, requiredness, nulls, and outliers before treating it as a contract.

Hub

Population Ecology, Biodiversity, and Food Web Calculators

Use educational ecology models to explore population growth, carrying capacity, species interactions, sampled biodiversity, and trophic energy transfer.

Hub

Authorized Webhook Capture and Endpoint Trust Checks

Capture and replay controlled webhook requests, inspect delivery evidence, and check the receiver HTTPS certificate without treating a valid certificate as proof of business trust.

Hub

Observability Debugging from Logs, Traces, Webhooks, and JSON Payloads

Parse logs, decode traces, inspect webhook/API evidence, explore JSON payloads, and extract recurring patterns before writing an incident-ready debugging note.

Home
Tools3212
Samples593
Visualizations471
Viewers103
Hubs239
Tags333
Images, Audio & Video657

Image, audio, and video processing, conversion, and optimization tools

Math, Date & Finance647

Calculators, numerics, date logic, statistics, and finance tools

Design & Color298

Color, layout, graphics, visual styling, and design helper tools

Text & Writing209

Writing, cleanup, formatting, extraction, and text analysis tools

Developer & Web193

Developer utilities, networking, web debugging, and automation helpers

Conversion & Encoding175

Format, file, archive, unit, and encoding conversion tools

Lead Generation Quiz Launch and Contact Handoff
Memorial Drafts: Family Review and Print Handoff
Private Habit Records: Backup, Restore and Sharing Review
Article to X and LinkedIn Drafts: Fact Review and Handoff
Markdown Interactive Deck Review and Offline Handoff

© 2026 Elysia Tools. All rights reserved.

DocsPricingAboutTerms of ServicePrivacy PolicyCookiesContact

Media

Chrome Web Store Screenshots Resized

Resize images to Chrome Web Store screenshot dimensions while preserving full content and aspect ratio for extension and app listings

Format Conversion

Web Push RFC 8030 Request + VAPID + RFC 8291 Payload Encryption Encoder

Encode a complete Web Push send: RFC 8291 aes128gcm payload encryption, RFC 8292 VAPID ES256 JWT, RFC 8030 headers, APNs/FCM cross-walk and decrypt round-trip verification.

Web & Internet

Web Search (SearXNG JSON)

Search the web through the s.stdlang.com SearXNG instance and return its JSON response for automation or downstream tools.

Design

Web Font Pairing Lab

Preview a heading + body Google Fonts pairing with weight and line-height controls, and copy a ready-to-paste CSS @import + variables snippet. Curated 22-face registry plus 7 proven pairing presets.

Network

IP Info

Get real information about IP addresses including location and ISP details using geolocation database

Media

Convert AVIF to GIF

Convert AVIF images to GIF format with animation support and optimization options

Media

Convert AVIF to WebP

Convert AVIF images to WebP format with advanced compression options and web optimization

Network

CIDR Calculator

Calculate network information from CIDR notation. Supports IPv4 and IPv6.

Java

Android Mobile Features Java Samples

Android Java mobile-specific features including device info, network status, and sensors

Kotlin

Android Mobile Features Kotlin Samples

Android Kotlin mobile-specific examples including device information, network status, and vibration control

Swift

macOS Mobile Features Swift Samples

macOS Swift mobile features examples including device information, network status, and vibration feedback

Python

Web Mobile Features Python Samples

Web Python mobile-specific features examples including device info, network status, and vibration

Rust

Web Mobile Features Rust Samples

Web Rust mobile-like features examples including device info, network status, and haptic feedback

TypeScript

Web Mobile Features TypeScript Samples

Web TypeScript mobile-specific features examples including device info, network status, and vibration