Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHDERUPTENFRES

Elysia Tools

导航

Go

Web Go 移动端功能示例

Web Go 移动端特定功能示例,包括设备信息、网络状态和振动

案例

这个案例集合中的条目

代码go简单

设备信息

获取设备型号、操作系统版本和其他设备属性

难度

6/10

预计时间

25 min

标签

go, web, mobile features

前置条件

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 ===")
}
代码go简单

网络状态

检查网络连接状态和类型

难度

6/10

预计时间

30 min

标签

go, web, mobile features

前置条件

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 ===")
}
代码go简单

振动

控制设备振动(支持有限,特定于平台)

难度

5/10

预计时间

20 min

标签

go, web, mobile features

前置条件

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")
}

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

专题

肾功能、透析与剂量模型核查

在教育场景中比较肾功能公式、透析充分性指标和肾脏相关用药计算,避免患者特异剂量或诊断建议。

专题

获授权 Webhook 捕获与接收端信任检查

在获授权的测试环境捕获并回放受控 Webhook 请求,分别检查投递证据和接收端 HTTPS 证书,不把证书有效误写成业务信任证明。

专题

用日志、链路、Webhook 和 JSON 载荷做可观测性调试

解析日志,解码调用链,检查 Webhook/API 证据,探索 JSON 载荷,并提取重复模式,形成可用于事故复盘的调试结论。

专题

视频交付格式转换:音频、媒体流、GIF、WebM 与 MP4

先按交付场景选择视频或动画格式,再提取所需的音频或视频流,并记录转换后的兼容性、质量和体积取舍。

首页
工具3212
案例593
可视化471
文件查看器103
专题239
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融647

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web193

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

潜客测验发布与联系人交接
讣告、悼词与纪念卡的家属复核及交付
本地习惯记录的备份、恢复演练与分享前检查
长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Media

Chrome网上应用商店截图调整

将图片调整为Chrome网上应用商店截图尺寸,同时保留完整内容和原始宽高比例

Format Conversion

Web Push RFC 8030 请求 + VAPID + RFC 8291 负载加密编码器

编码完整的 Web Push 发送流程:RFC 8291 aes128gcm 负载加密、RFC 8292 VAPID ES256 JWT、RFC 8030 头部、APNs/FCM 头部对照与解密往返验证。

Web & Internet

Web 搜索(SearXNG JSON)

通过 s.stdlang.com 的 SearXNG 实例搜索网页,返回 JSON 结果供自动化或后续工具使用。

Design

网页字体配对实验室

并排预览 标题 + 正文 的 Google 字体配对,调节字重与行高,复制即可粘贴的 CSS @import + 变量代码。精选 22 款字体及 7 组经典搭配预设。

Network

IP信息查询

使用地理位置数据库获取IP地址的真实信息,包括位置和ISP详情

Media

AVIF转GIF转换器

将AVIF图像转换为GIF格式,支持动画和优化选项

Media

AVIF转WebP转换器

将AVIF图像转换为WebP格式,支持高级压缩选项和网页优化

Network

CIDR计算器

从CIDR表示法计算网络信息。支持IPv4和IPv6。

Java

Android Java 移动功能示例

Android Java 移动端专用功能示例,包括设备信息、网络状态和传感器

Kotlin

Android Kotlin 移动端功能示例

Android Kotlin 移动端功能示例,包括设备信息、网络状态和振动控制

Swift

macOS 移动端功能 Swift 示例

macOS Swift 移动端功能示例,包括设备信息、网络状态和振动反馈

Python

Web Python 移动端功能示例

Web Python 移动端功能示例,包括设备信息、网络状态和振动提示

Rust

Web Rust 移动端功能示例

Web Rust 移动端功能示例,包括设备信息、网络状态和触觉反馈

TypeScript

Web TypeScript 移动端功能示例

Web TypeScript 移动端功能示例,包括设备信息、网络状态和振动提示