国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁(yè) 後端開(kāi)發(fā) Golang 使用 Go 建立跨平臺(tái)系統(tǒng)服務(wù):逐步指南

使用 Go 建立跨平臺(tái)系統(tǒng)服務(wù):逐步指南

Nov 04, 2024 am 08:18 AM

Building Cross-Platform System Services in Go: A Step-by-Step Guide

什麼是系統(tǒng)服務(wù)?

系統(tǒng)服務(wù)是在背景運(yùn)行的輕量級(jí)程序,無(wú)需圖形使用者介面。它們?cè)谙到y(tǒng)啟動(dòng)期間自動(dòng)啟動(dòng)並獨(dú)立運(yùn)作。它們的生命週期(包括啟動(dòng)、停止和重新啟動(dòng)等操作)由 Windows 上的服務(wù)控制管理器、Linux 上的 systemd(在大多數(shù) detro 中)和 macOS 上的 launchd 管理。

與標(biāo)準(zhǔn)應(yīng)用程式不同,服務(wù)是為連續(xù)操作而設(shè)計(jì)的,對(duì)於監(jiān)控、日誌記錄和其他後臺(tái)進(jìn)程等任務(wù)至關(guān)重要。在 Linux 上,這些服務(wù)通常稱(chēng)為守護(hù)進(jìn)程,而在 macOS 上,它們稱(chēng)為啟動(dòng)代理或守護(hù)程式。

為什麼選擇建築系統(tǒng)服務(wù)*? *

創(chuàng)建跨平臺(tái)系統(tǒng)服務(wù)需要一種平衡效率、可用性和可靠性的語(yǔ)言。 Go 在這方面表現(xiàn)優(yōu)異有幾個(gè)原因:

  • 同時(shí)與效能:Go 的 goroutine 可以輕鬆地同時(shí)執(zhí)行多個(gè)任務(wù),從而提高不同平臺(tái)上的效率和速度。與強(qiáng)大的標(biāo)準(zhǔn)庫(kù)相結(jié)合,最大限度地減少了外部依賴(lài)並增強(qiáng)了跨平臺(tái)相容性。

  • 記憶體管理與穩(wěn)定性:Go 的垃圾收集可以防止記憶體洩漏,並保持系統(tǒng)穩(wěn)定。其清晰的錯(cuò)誤處理也使得調(diào)試複雜的服務(wù)變得更加容易。

  • 簡(jiǎn)單性和可維護(hù)性:Go 清晰的語(yǔ)法簡(jiǎn)化了服務(wù)的編寫(xiě)和維護(hù)。它能夠產(chǎn)生靜態(tài)連結(jié)的二進(jìn)位文件,從而產(chǎn)生包含所有必要依賴(lài)項(xiàng)的單一可執(zhí)行文件,從而無(wú)需單獨(dú)的運(yùn)行時(shí)環(huán)境。

  • 交叉編譯和靈活性:Go 對(duì)交叉編譯的支援允許從單一程式碼庫(kù)為各種作業(yè)系統(tǒng)建立可執(zhí)行檔。透過(guò) CGO,Go 可以與低階系統(tǒng) API(例如 Win32 和 Objective-C)進(jìn)行交互,為開(kāi)發(fā)人員提供利用本機(jī)功能的靈活性。

用 Go 寫(xiě)服務(wù)

此程式碼演練假設(shè)您的電腦上安裝了 GO,並且您對(duì) GO 的語(yǔ)法有基本了解,如果沒(méi)有,我強(qiáng)烈建議您參觀一下。

項(xiàng)目概況

go-service/
├── Makefile                 # Build and installation automation
├── cmd/
│   └── service/
│       └── main.go          # Main entry point with CLI flags and command handling
├── internal/
│   ├── service/
│   │   └── service.go       # Core service implementation
│   └── platform/            # Platform-specific implementations
│       ├── config.go        # Configuration constants
│       ├── service.go       # Cross-platform service interface
│       ├── windows.go       # Windows-specific service management
│       ├── linux.go         # Linux-specific systemd service management
│       └── darwin.go        # macOS-specific launchd service management
└── go.mod                   # Go module definition

第 1 步:定義配置

初始化Go模組:

go mod init go-service

在internal/platform目錄下的config.go定義配置常數(shù)。該文件集中了所有可配置值,可以輕鬆調(diào)整設(shè)定。

檔案:internal/platform/config.go

package main

const (
 ServiceName    = "go-service"                                                      //Update your service name
 ServiceDisplay = "Go Service"                                                      // Update your display name
 ServiceDesc    = "A service that appends 'Hello World' to a file every 5 minutes." // Update your Service Description
 LogFileName    = "go-service.log"                                              // Update your Log file name
)

func GetInstallDir() string {
 switch runtime.GOOS {
 case "darwin":
  return "/usr/local/opt/go-service"
 case "linux":
  return "/opt/go-service"
 case "windows":
  return filepath.Join(os.Getenv("ProgramData"), ServiceName)
 default:
  return ""
 }
}

func copyFile(src, dst string) error {
 source, err := os.Open(src)
 if err != nil {
  return fmt.Errorf("failed to open source file: %w", err)
 }
 defer source.Close()

 destination, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
 if err != nil {
  return fmt.Errorf("failed to create destination file: %w", err)
 }
 defer destination.Close()

 _, err = io.Copy(destination, source)
 return err
}

主要特點(diǎn):

  • 將在特定於平臺(tái)的服務(wù)配置期間使用的服務(wù)常數(shù)。

  • GetInstallDir() 為每個(gè)作業(yè)系統(tǒng)提供適當(dāng)?shù)姆?wù)安裝和日誌檔案路徑。

  • 在服務(wù)安裝過(guò)程中使用copyFile()將執(zhí)行檔複製到GetInstallDir()提供的特定路徑。

第 2 步:定義核心服務(wù)邏輯

在內(nèi)部/服務(wù)中,實(shí)現(xiàn)您的服務(wù)的核心功能。核心服務(wù)實(shí)現(xiàn)處理我們服務(wù)的主要功能。

在此範(fàn)例中,服務(wù)每 5 分鐘將「Hello World」附加到使用者主目錄中的檔案中。

檔案:內(nèi)部/service/service.go

服務(wù)結(jié)構(gòu)

go-service/
├── Makefile                 # Build and installation automation
├── cmd/
│   └── service/
│       └── main.go          # Main entry point with CLI flags and command handling
├── internal/
│   ├── service/
│   │   └── service.go       # Core service implementation
│   └── platform/            # Platform-specific implementations
│       ├── config.go        # Configuration constants
│       ├── service.go       # Cross-platform service interface
│       ├── windows.go       # Windows-specific service management
│       ├── linux.go         # Linux-specific systemd service management
│       └── darwin.go        # macOS-specific launchd service management
└── go.mod                   # Go module definition

服務(wù)創(chuàng)造

go mod init go-service

服務(wù)生命週期

服務(wù)實(shí)現(xiàn)生命週期管理的 Start 和 Stop 方法:

package main

const (
 ServiceName    = "go-service"                                                      //Update your service name
 ServiceDisplay = "Go Service"                                                      // Update your display name
 ServiceDesc    = "A service that appends 'Hello World' to a file every 5 minutes." // Update your Service Description
 LogFileName    = "go-service.log"                                              // Update your Log file name
)

func GetInstallDir() string {
 switch runtime.GOOS {
 case "darwin":
  return "/usr/local/opt/go-service"
 case "linux":
  return "/opt/go-service"
 case "windows":
  return filepath.Join(os.Getenv("ProgramData"), ServiceName)
 default:
  return ""
 }
}

func copyFile(src, dst string) error {
 source, err := os.Open(src)
 if err != nil {
  return fmt.Errorf("failed to open source file: %w", err)
 }
 defer source.Close()

 destination, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
 if err != nil {
  return fmt.Errorf("failed to create destination file: %w", err)
 }
 defer destination.Close()

 _, err = io.Copy(destination, source)
 return err
}

主服務(wù)循環(huán)

type Service struct {
 logFile string
 stop    chan struct{}
 wg      sync.WaitGroup
 started bool
 mu      sync.Mutex
}

run方法處理核心服務(wù)邏輯:

主要特點(diǎn):

  • 使用程式碼進(jìn)行基於時(shí)間間隔的執(zhí)行

  • 上下文取消支援

  • 優(yōu)雅的關(guān)閉處理

  • 錯(cuò)誤記錄

日誌寫(xiě)入

此服務(wù)每 5 分鐘附加一個(gè)帶有時(shí)間戳記的「Hello World」

func New() (*Service, error) {
 installDir := platform.GetInstallDir()
 if installDir == "" {
  return nil, fmt.Errorf("unsupported operating system: %s", runtime.GOOS)
 }

 logFile := filepath.Join(installDir, "logs", platform.LogFileName)

 return &Service{
  logFile: logFile,
  stop:    make(chan struct{}),
 }, nil
}

步驟 3:建立特定於平臺(tái)的服務(wù)配置

internal/platform 目錄包含用於安裝、卸載和管理服務(wù)的特定於平臺(tái)的配置。

macOS (darwin.go)

在 darwin.go 中,定義用於建立 .plist 檔案的 macOS 特定邏輯,該檔案使用 launchctl 處理服務(wù)安裝和卸載。

檔案:internal/platform/darwin.go

// Start the service
func (s *Service) Start(ctx context.Context) error {
 s.mu.Lock()
 if s.started {
  s.mu.Unlock()
  return fmt.Errorf("service already started")
 }
 s.started = true
 s.mu.Unlock()

 if err := os.MkdirAll(filepath.Dir(s.logFile), 0755); err != nil {
  return fmt.Errorf("failed to create log directory: %w", err)
 }

 s.wg.Add(1)
 go s.run(ctx)

 return nil
}

// Stop the service gracefully
func (s *Service) Stop() error {
 s.mu.Lock()
 if !s.started {
  s.mu.Unlock()
  return fmt.Errorf("service not started")
 }
 s.mu.Unlock()

 close(s.stop)
 s.wg.Wait()

 s.mu.Lock()
 s.started = false
 s.mu.Unlock()

 return nil
}

Linux (linux.go)

在 Linux 上,我們使用 systemd 來(lái)管理服務(wù)。定義 .service 檔案和相關(guān)方法。

文件:internal/platform/linux.go

func (s *Service) run(ctx context.Context) {
 defer s.wg.Done()
 log.Printf("Service started, logging to: %s\n", s.logFile)

 ticker := time.NewTicker(5 * time.Minute)
 defer ticker.Stop()

 if err := s.writeLog(); err != nil {
  log.Printf("Error writing initial log: %v\n", err)
 }

 for {
  select {
  case <-ctx.Done():
   log.Println("Service stopping due to context cancellation")
   return
  case <-s.stop:
   log.Println("Service stopping due to stop signal")
   return
  case <-ticker.C:
   if err := s.writeLog(); err != nil {
    log.Printf("Error writing log: %v\n", err)
   }
  }
 }
}

Windows (windows.go)

對(duì)於 Windows,使用 sc 指令安裝和解除安裝服務(wù)。

文件:internal/platform/windows.go

func (s *Service) writeLog() error {
 f, err := os.OpenFile(s.logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
 if err != nil {
  return fmt.Errorf("failed to open log file: %w", err)
 }
 defer f.Close()

 _, err = f.WriteString(fmt.Sprintf("[%s] Hello World\n", time.Now().Format(time.RFC3339)))
 if err != nil {
  return fmt.Errorf("failed to write to log file: %w", err)
 }
 return nil
}

第 4 步:主文件設(shè)定 (main.go)

最後,在 cmd/service/main.go 中設(shè)定 main.go 來(lái)處理安裝、解除安裝和啟動(dòng)服務(wù)。

檔案:cmd/service/main.go

package platform

import (
 "fmt"
 "os"
 "os/exec"
 "path/filepath"
)

type darwinService struct{}

const plistTemplate = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>%s</string>
    <key>ProgramArguments</key>
    <array>
        <string>%s</string>
        <string>-run</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>WorkingDirectory</key>
    <string>%s</string>
</dict>
</plist>`

func (s *darwinService) Install(execPath string) error {
 installDir := GetInstallDir()
 if err := os.MkdirAll(installDir, 0755); err != nil {
  return fmt.Errorf("failed to create installation directory: %w", err)
 }

 // Copy binary to installation directory
 installedBinary := filepath.Join(installDir, "bin", filepath.Base(execPath))
 if err := os.MkdirAll(filepath.Dir(installedBinary), 0755); err != nil {
  return fmt.Errorf("failed to create bin directory: %w", err)
 }

 if err := copyFile(execPath, installedBinary); err != nil {
  return fmt.Errorf("failed to copy binary: %w", err)
 }

 plistPath := filepath.Join("/Library/LaunchDaemons", ServiceName+".plist")
 content := fmt.Sprintf(plistTemplate, ServiceName, installedBinary, installDir)

 if err := os.WriteFile(plistPath, []byte(content), 0644); err != nil {
  return fmt.Errorf("failed to write plist file: %w", err)
 }

 if err := exec.Command("launchctl", "load", plistPath).Run(); err != nil {
  return fmt.Errorf("failed to load service: %w", err)
 }
 return nil
}

func (s *darwinService) Uninstall() error {
 plistPath := filepath.Join("/Library/LaunchDaemons", ServiceName+".plist")

 if err := exec.Command("launchctl", "unload", plistPath).Run(); err != nil {
  return fmt.Errorf("failed to unload service: %w", err)
 }

 if err := os.Remove(plistPath); err != nil {
  return fmt.Errorf("failed to remove plist file: %w", err)
 }
 return nil
}

func (s *darwinService) Status() (bool, error) {
 err := exec.Command("launchctl", "list", ServiceName).Run()
 return err == nil, nil
}

func (s *darwinService) Start() error {
 if err := exec.Command("launchctl", "start", ServiceName).Run(); err != nil {
  return fmt.Errorf("failed to start service: %w", err)
 }
 return nil
}

func (s *darwinService) Stop() error {
 if err := exec.Command("launchctl", "stop", ServiceName).Run(); err != nil {
  return fmt.Errorf("failed to stop service: %w", err)
 }
 return nil
}

建構(gòu)和管理您的服務(wù)

要為不同的作業(yè)系統(tǒng)建立服務(wù),請(qǐng)使用 GOOS 和 GOARCH 環(huán)境變數(shù)。例如,要為 Windows 建置:

package platform

import (
 "fmt"
 "os"
 "os/exec"
 "path/filepath"
)

type linuxService struct{}

const systemdServiceTemplate = `[Unit]
Description=%s

[Service]
ExecStart=%s -run
Restart=always
User=root
WorkingDirectory=%s

[Install]
WantedBy=multi-user.target
`

func (s *linuxService) Install(execPath string) error {
 installDir := GetInstallDir()
 if err := os.MkdirAll(installDir, 0755); err != nil {
  return fmt.Errorf("failed to create installation directory: %w", err)
 }

 installedBinary := filepath.Join(installDir, "bin", filepath.Base(execPath))
 if err := os.MkdirAll(filepath.Dir(installedBinary), 0755); err != nil {
  return fmt.Errorf("failed to create bin directory: %w", err)
 }

 if err := copyFile(execPath, installedBinary); err != nil {
  return fmt.Errorf("failed to copy binary: %w", err)
 }

 servicePath := filepath.Join("/etc/systemd/system", ServiceName+".service")
 content := fmt.Sprintf(systemdServiceTemplate, ServiceDesc, installedBinary, installDir)

 if err := os.WriteFile(servicePath, []byte(content), 0644); err != nil {
  return fmt.Errorf("failed to write service file: %w", err)
 }

 commands := [][]string{
  {"systemctl", "daemon-reload"},
  {"systemctl", "enable", ServiceName},
  {"systemctl", "start", ServiceName},
 }

 for _, args := range commands {
  if err := exec.Command(args[0], args[1:]...).Run(); err != nil {
   return fmt.Errorf("failed to execute %s: %w", args[0], err)
  }
 }
 return nil
}

func (s *linuxService) Uninstall() error {
 _ = exec.Command("systemctl", "stop", ServiceName).Run()
 _ = exec.Command("systemctl", "disable", ServiceName).Run()

 servicePath := filepath.Join("/etc/systemd/system", ServiceName+".service")
 if err := os.Remove(servicePath); err != nil {
  return fmt.Errorf("failed to remove service file: %w", err)
 }
 return nil
}

func (s *linuxService) Status() (bool, error) {
 output, err := exec.Command("systemctl", "is-active", ServiceName).Output()
 if err != nil {
  return false, nil
 }
 return string(output) == "active\n", nil
}

func (s *linuxService) Start() error {
 if err := exec.Command("systemctl", "start", ServiceName).Run(); err != nil {
  return fmt.Errorf("failed to start service: %w", err)
 }
 return nil
}

func (s *linuxService) Stop() error {
 if err := exec.Command("systemctl", "stop", ServiceName).Run(); err != nil {
  return fmt.Errorf("failed to stop service: %w", err)
 }
 return nil
}

對(duì)於 Linux:

package platform

import (
 "fmt"
 "os"
 "os/exec"
 "path/filepath"
 "strings"
)

type windowsService struct{}

func (s *windowsService) Install(execPath string) error {
 installDir := GetInstallDir()
 if err := os.MkdirAll(installDir, 0755); err != nil {
  return fmt.Errorf("failed to create installation directory: %w", err)
 }

 installedBinary := filepath.Join(installDir, "bin", filepath.Base(execPath))
 if err := os.MkdirAll(filepath.Dir(installedBinary), 0755); err != nil {
  return fmt.Errorf("failed to create bin directory: %w", err)
 }

 if err := copyFile(execPath, installedBinary); err != nil {
  return fmt.Errorf("failed to copy binary: %w", err)
 }

 cmd := exec.Command("sc", "create", ServiceName,
  "binPath=", fmt.Sprintf("\"%s\" -run", installedBinary),
  "DisplayName=", ServiceDisplay,
  "start=", "auto",
  "obj=", "LocalSystem")

 if err := cmd.Run(); err != nil {
  return fmt.Errorf("failed to create service: %w", err)
 }

 descCmd := exec.Command("sc", "description", ServiceName, ServiceDesc)
 if err := descCmd.Run(); err != nil {
  return fmt.Errorf("failed to set service description: %w", err)
 }

 if err := exec.Command("sc", "start", ServiceName).Run(); err != nil {
  return fmt.Errorf("failed to start service: %w", err)
 }
 return nil
}

func (s *windowsService) Uninstall() error {
 _ = exec.Command("sc", "stop", ServiceName).Run()
 if err := exec.Command("sc", "delete", ServiceName).Run(); err != nil {
  return fmt.Errorf("failed to delete service: %w", err)
 }

 // Clean up installation directory
 installDir := GetInstallDir()
 if err := os.RemoveAll(installDir); err != nil {
  return fmt.Errorf("failed to remove installation directory: %w", err)
 }
 return nil
}
func (s *windowsService) Status() (bool, error) {
 output, err := exec.Command("sc", "query", ServiceName).Output()
 if err != nil {
  return false, nil
 }
 return strings.Contains(string(output), "RUNNING"), nil
}

func (s *windowsService) Start() error {
 if err := exec.Command("sc", "start", ServiceName).Run(); err != nil {
  return fmt.Errorf("failed to start service: %w", err)
 }
 return nil
}

func (s *windowsService) Stop() error {
 if err := exec.Command("sc", "stop", ServiceName).Run(); err != nil {
  return fmt.Errorf("failed to stop service: %w", err)
 }
 return nil
}

對(duì)於 macOS:

go-service/
├── Makefile                 # Build and installation automation
├── cmd/
│   └── service/
│       └── main.go          # Main entry point with CLI flags and command handling
├── internal/
│   ├── service/
│   │   └── service.go       # Core service implementation
│   └── platform/            # Platform-specific implementations
│       ├── config.go        # Configuration constants
│       ├── service.go       # Cross-platform service interface
│       ├── windows.go       # Windows-specific service management
│       ├── linux.go         # Linux-specific systemd service management
│       └── darwin.go        # macOS-specific launchd service management
└── go.mod                   # Go module definition

管理您的服務(wù)

為對(duì)應(yīng)的作業(yè)系統(tǒng)建置服務(wù)後,您可以使用以下命令對(duì)其進(jìn)行管理。

注意: 確保使用 root 權(quán)限執(zhí)行指令,因?yàn)檫@些操作需要在所有平臺(tái)上提升權(quán)限。

  • 安裝服務(wù):使用 --install 標(biāo)誌來(lái)安裝服務(wù)。
go mod init go-service
  • 檢查狀態(tài):要檢查服務(wù)是否正在執(zhí)行,請(qǐng)使用:
package main

const (
 ServiceName    = "go-service"                                                      //Update your service name
 ServiceDisplay = "Go Service"                                                      // Update your display name
 ServiceDesc    = "A service that appends 'Hello World' to a file every 5 minutes." // Update your Service Description
 LogFileName    = "go-service.log"                                              // Update your Log file name
)

func GetInstallDir() string {
 switch runtime.GOOS {
 case "darwin":
  return "/usr/local/opt/go-service"
 case "linux":
  return "/opt/go-service"
 case "windows":
  return filepath.Join(os.Getenv("ProgramData"), ServiceName)
 default:
  return ""
 }
}

func copyFile(src, dst string) error {
 source, err := os.Open(src)
 if err != nil {
  return fmt.Errorf("failed to open source file: %w", err)
 }
 defer source.Close()

 destination, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
 if err != nil {
  return fmt.Errorf("failed to create destination file: %w", err)
 }
 defer destination.Close()

 _, err = io.Copy(destination, source)
 return err
}
  • 卸載服務(wù):如果需要?jiǎng)h除服務(wù),請(qǐng)使用 --uninstall 標(biāo)誌:
type Service struct {
 logFile string
 stop    chan struct{}
 wg      sync.WaitGroup
 started bool
 mu      sync.Mutex
}

使用 TaskFile 建置和管理您的服務(wù)(可選)

雖然您可以使用 Go 命令和標(biāo)誌來(lái)建置和管理服務(wù),但我強(qiáng)烈建議使用 TaskFile。它使這些過(guò)程自動(dòng)化並提供:

  • 所有平臺(tái)上一致的命令

  • 基於 YAML 的簡(jiǎn)單設(shè)定

  • 內(nèi)建依賴(lài)管理

設(shè)定任務(wù)

首先,檢查T(mén)ask是否已安裝:

func New() (*Service, error) {
 installDir := platform.GetInstallDir()
 if installDir == "" {
  return nil, fmt.Errorf("unsupported operating system: %s", runtime.GOOS)
 }

 logFile := filepath.Join(installDir, "logs", platform.LogFileName)

 return &Service{
  logFile: logFile,
  stop:    make(chan struct{}),
 }, nil
}

如果不存在,請(qǐng)使用以下指令安裝:

macOS

// Start the service
func (s *Service) Start(ctx context.Context) error {
 s.mu.Lock()
 if s.started {
  s.mu.Unlock()
  return fmt.Errorf("service already started")
 }
 s.started = true
 s.mu.Unlock()

 if err := os.MkdirAll(filepath.Dir(s.logFile), 0755); err != nil {
  return fmt.Errorf("failed to create log directory: %w", err)
 }

 s.wg.Add(1)
 go s.run(ctx)

 return nil
}

// Stop the service gracefully
func (s *Service) Stop() error {
 s.mu.Lock()
 if !s.started {
  s.mu.Unlock()
  return fmt.Errorf("service not started")
 }
 s.mu.Unlock()

 close(s.stop)
 s.wg.Wait()

 s.mu.Lock()
 s.started = false
 s.mu.Unlock()

 return nil
}

Linux

func (s *Service) run(ctx context.Context) {
 defer s.wg.Done()
 log.Printf("Service started, logging to: %s\n", s.logFile)

 ticker := time.NewTicker(5 * time.Minute)
 defer ticker.Stop()

 if err := s.writeLog(); err != nil {
  log.Printf("Error writing initial log: %v\n", err)
 }

 for {
  select {
  case <-ctx.Done():
   log.Println("Service stopping due to context cancellation")
   return
  case <-s.stop:
   log.Println("Service stopping due to stop signal")
   return
  case <-ticker.C:
   if err := s.writeLog(); err != nil {
    log.Printf("Error writing log: %v\n", err)
   }
  }
 }
}

Windows

func (s *Service) writeLog() error {
 f, err := os.OpenFile(s.logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
 if err != nil {
  return fmt.Errorf("failed to open log file: %w", err)
 }
 defer f.Close()

 _, err = f.WriteString(fmt.Sprintf("[%s] Hello World\n", time.Now().Format(time.RFC3339)))
 if err != nil {
  return fmt.Errorf("failed to write to log file: %w", err)
 }
 return nil
}

任務(wù)配置

在專(zhuān)案根目錄中建立一個(gè) Taskfile.yml:

package platform

import (
 "fmt"
 "os"
 "os/exec"
 "path/filepath"
)

type darwinService struct{}

const plistTemplate = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>%s</string>
    <key>ProgramArguments</key>
    <array>
        <string>%s</string>
        <string>-run</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>WorkingDirectory</key>
    <string>%s</string>
</dict>
</plist>`

func (s *darwinService) Install(execPath string) error {
 installDir := GetInstallDir()
 if err := os.MkdirAll(installDir, 0755); err != nil {
  return fmt.Errorf("failed to create installation directory: %w", err)
 }

 // Copy binary to installation directory
 installedBinary := filepath.Join(installDir, "bin", filepath.Base(execPath))
 if err := os.MkdirAll(filepath.Dir(installedBinary), 0755); err != nil {
  return fmt.Errorf("failed to create bin directory: %w", err)
 }

 if err := copyFile(execPath, installedBinary); err != nil {
  return fmt.Errorf("failed to copy binary: %w", err)
 }

 plistPath := filepath.Join("/Library/LaunchDaemons", ServiceName+".plist")
 content := fmt.Sprintf(plistTemplate, ServiceName, installedBinary, installDir)

 if err := os.WriteFile(plistPath, []byte(content), 0644); err != nil {
  return fmt.Errorf("failed to write plist file: %w", err)
 }

 if err := exec.Command("launchctl", "load", plistPath).Run(); err != nil {
  return fmt.Errorf("failed to load service: %w", err)
 }
 return nil
}

func (s *darwinService) Uninstall() error {
 plistPath := filepath.Join("/Library/LaunchDaemons", ServiceName+".plist")

 if err := exec.Command("launchctl", "unload", plistPath).Run(); err != nil {
  return fmt.Errorf("failed to unload service: %w", err)
 }

 if err := os.Remove(plistPath); err != nil {
  return fmt.Errorf("failed to remove plist file: %w", err)
 }
 return nil
}

func (s *darwinService) Status() (bool, error) {
 err := exec.Command("launchctl", "list", ServiceName).Run()
 return err == nil, nil
}

func (s *darwinService) Start() error {
 if err := exec.Command("launchctl", "start", ServiceName).Run(); err != nil {
  return fmt.Errorf("failed to start service: %w", err)
 }
 return nil
}

func (s *darwinService) Stop() error {
 if err := exec.Command("launchctl", "stop", ServiceName).Run(); err != nil {
  return fmt.Errorf("failed to stop service: %w", err)
 }
 return nil
}

使用任務(wù)命令

服務(wù)管理(需要root/管理員權(quán)限):

package platform

import (
 "fmt"
 "os"
 "os/exec"
 "path/filepath"
)

type linuxService struct{}

const systemdServiceTemplate = `[Unit]
Description=%s

[Service]
ExecStart=%s -run
Restart=always
User=root
WorkingDirectory=%s

[Install]
WantedBy=multi-user.target
`

func (s *linuxService) Install(execPath string) error {
 installDir := GetInstallDir()
 if err := os.MkdirAll(installDir, 0755); err != nil {
  return fmt.Errorf("failed to create installation directory: %w", err)
 }

 installedBinary := filepath.Join(installDir, "bin", filepath.Base(execPath))
 if err := os.MkdirAll(filepath.Dir(installedBinary), 0755); err != nil {
  return fmt.Errorf("failed to create bin directory: %w", err)
 }

 if err := copyFile(execPath, installedBinary); err != nil {
  return fmt.Errorf("failed to copy binary: %w", err)
 }

 servicePath := filepath.Join("/etc/systemd/system", ServiceName+".service")
 content := fmt.Sprintf(systemdServiceTemplate, ServiceDesc, installedBinary, installDir)

 if err := os.WriteFile(servicePath, []byte(content), 0644); err != nil {
  return fmt.Errorf("failed to write service file: %w", err)
 }

 commands := [][]string{
  {"systemctl", "daemon-reload"},
  {"systemctl", "enable", ServiceName},
  {"systemctl", "start", ServiceName},
 }

 for _, args := range commands {
  if err := exec.Command(args[0], args[1:]...).Run(); err != nil {
   return fmt.Errorf("failed to execute %s: %w", args[0], err)
  }
 }
 return nil
}

func (s *linuxService) Uninstall() error {
 _ = exec.Command("systemctl", "stop", ServiceName).Run()
 _ = exec.Command("systemctl", "disable", ServiceName).Run()

 servicePath := filepath.Join("/etc/systemd/system", ServiceName+".service")
 if err := os.Remove(servicePath); err != nil {
  return fmt.Errorf("failed to remove service file: %w", err)
 }
 return nil
}

func (s *linuxService) Status() (bool, error) {
 output, err := exec.Command("systemctl", "is-active", ServiceName).Output()
 if err != nil {
  return false, nil
 }
 return string(output) == "active\n", nil
}

func (s *linuxService) Start() error {
 if err := exec.Command("systemctl", "start", ServiceName).Run(); err != nil {
  return fmt.Errorf("failed to start service: %w", err)
 }
 return nil
}

func (s *linuxService) Stop() error {
 if err := exec.Command("systemctl", "stop", ServiceName).Run(); err != nil {
  return fmt.Errorf("failed to stop service: %w", err)
 }
 return nil
}

為您的平臺(tái)建置:

package platform

import (
 "fmt"
 "os"
 "os/exec"
 "path/filepath"
 "strings"
)

type windowsService struct{}

func (s *windowsService) Install(execPath string) error {
 installDir := GetInstallDir()
 if err := os.MkdirAll(installDir, 0755); err != nil {
  return fmt.Errorf("failed to create installation directory: %w", err)
 }

 installedBinary := filepath.Join(installDir, "bin", filepath.Base(execPath))
 if err := os.MkdirAll(filepath.Dir(installedBinary), 0755); err != nil {
  return fmt.Errorf("failed to create bin directory: %w", err)
 }

 if err := copyFile(execPath, installedBinary); err != nil {
  return fmt.Errorf("failed to copy binary: %w", err)
 }

 cmd := exec.Command("sc", "create", ServiceName,
  "binPath=", fmt.Sprintf("\"%s\" -run", installedBinary),
  "DisplayName=", ServiceDisplay,
  "start=", "auto",
  "obj=", "LocalSystem")

 if err := cmd.Run(); err != nil {
  return fmt.Errorf("failed to create service: %w", err)
 }

 descCmd := exec.Command("sc", "description", ServiceName, ServiceDesc)
 if err := descCmd.Run(); err != nil {
  return fmt.Errorf("failed to set service description: %w", err)
 }

 if err := exec.Command("sc", "start", ServiceName).Run(); err != nil {
  return fmt.Errorf("failed to start service: %w", err)
 }
 return nil
}

func (s *windowsService) Uninstall() error {
 _ = exec.Command("sc", "stop", ServiceName).Run()
 if err := exec.Command("sc", "delete", ServiceName).Run(); err != nil {
  return fmt.Errorf("failed to delete service: %w", err)
 }

 // Clean up installation directory
 installDir := GetInstallDir()
 if err := os.RemoveAll(installDir); err != nil {
  return fmt.Errorf("failed to remove installation directory: %w", err)
 }
 return nil
}
func (s *windowsService) Status() (bool, error) {
 output, err := exec.Command("sc", "query", ServiceName).Output()
 if err != nil {
  return false, nil
 }
 return strings.Contains(string(output), "RUNNING"), nil
}

func (s *windowsService) Start() error {
 if err := exec.Command("sc", "start", ServiceName).Run(); err != nil {
  return fmt.Errorf("failed to start service: %w", err)
 }
 return nil
}

func (s *windowsService) Stop() error {
 if err := exec.Command("sc", "stop", ServiceName).Run(); err != nil {
  return fmt.Errorf("failed to stop service: %w", err)
 }
 return nil
}

跨平臺(tái)建置:

package main

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

 "go-service/internal/platform"
 "go-service/internal/service"
)

func main() {
 log.SetFlags(log.LstdFlags | log.Lmicroseconds)

 install := flag.Bool("install", false, "Install the service")
 uninstall := flag.Bool("uninstall", false, "Uninstall the service")
 status := flag.Bool("status", false, "Check service status")
 start := flag.Bool("start", false, "Start the service")
 stop := flag.Bool("stop", false, "Stop the service")
 runWorker := flag.Bool("run", false, "Run the service worker")
 flag.Parse()

 if err := handleCommand(*install, *uninstall, *status, *start, *stop, *runWorker); err != nil {
  log.Fatal(err)
 }
}

func handleCommand(install, uninstall, status, start, stop, runWorker bool) error {
 platformSvc, err := platform.NewService()
 if err != nil {
  return err
 }

 execPath, err := os.Executable()
 if err != nil {
  return fmt.Errorf("failed to get executable path: %w", err)
 }

 switch {
 case install:
  return platformSvc.Install(execPath)
 case uninstall:
  return platformSvc.Uninstall()
 case status:
  running, err := platformSvc.Status()
  if err != nil {
   return err
  }
  fmt.Printf("Service is %s\n", map[bool]string{true: "running", false: "stopped"}[running])
  return nil
 case start:
  return platformSvc.Start()
 case stop:
  return platformSvc.Stop()
 case runWorker:
  return runService()
 default:
  return fmt.Errorf("no command specified")
 }
}

func runService() error {
 svc, err := service.New()
 if err != nil {
  return fmt.Errorf("failed to create service: %w", err)
 }

 ctx, cancel := context.WithCancel(context.Background())
 defer cancel()

 sigChan := make(chan os.Signal, 1)
 signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

 log.Println("Starting service...")
 if err := svc.Start(ctx); err != nil {
  return fmt.Errorf("failed to start service: %w", err)
 }

 log.Println("Service started, waiting for shutdown signal...")
 <-sigChan
 log.Println("Shutdown signal received, stopping service...")

 if err := svc.Stop(); err != nil {
  return fmt.Errorf("failed to stop service: %w", err)
 }
 log.Println("Service stopped successfully")
 return nil
}

列出所有可用任務(wù):

GOOS=windows GOARCH=amd64 go build -ldflags "-s -w" -o go-service.exe ./cmd/service

結(jié)論

透過(guò)遵循這種結(jié)構(gòu)化方法,您可以在 Go 中創(chuàng)建一個(gè)乾淨(jìng)且模組化的服務(wù),該服務(wù)可以跨多個(gè)平臺(tái)無(wú)縫運(yùn)行。每個(gè)平臺(tái)的具體資訊都隔離在各自的檔案中,並且 main.go 檔案保持簡(jiǎn)單且易於維護(hù)。

完整程式碼請(qǐng)參考我在 GitHub 上的 Go 服務(wù)儲(chǔ)存庫(kù)。

以上是使用 Go 建立跨平臺(tái)系統(tǒng)服務(wù):逐步指南的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請(qǐng)聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線(xiàn)上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開(kāi)發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)程式碼編輯軟體(SublimeText3)

熱門(mén)話(huà)題

Laravel 教程
1597
29
PHP教程
1488
72
是Golang前端還是後端 是Golang前端還是後端 Jul 08, 2025 am 01:44 AM

Golang主要用於後端開(kāi)發(fā),但也能在前端領(lǐng)域間接發(fā)揮作用。其設(shè)計(jì)目標(biāo)聚焦高性能、並發(fā)處理和系統(tǒng)級(jí)編程,適合構(gòu)建API服務(wù)器、微服務(wù)、分佈式系統(tǒng)、數(shù)據(jù)庫(kù)操作及CLI工具等後端應(yīng)用。雖然Golang不是網(wǎng)頁(yè)前端的主流語(yǔ)言,但可通過(guò)GopherJS編譯成JavaScript、通過(guò)TinyGo運(yùn)行於WebAssembly,或搭配模板引擎生成HTML頁(yè)面來(lái)參與前端開(kāi)發(fā)。然而,現(xiàn)代前端開(kāi)發(fā)仍需依賴(lài)JavaScript/TypeScript及其生態(tài)。因此,Golang更適合以高性能後端為核心的技術(shù)棧選擇。

如何在Golang中構(gòu)建GraphQl API 如何在Golang中構(gòu)建GraphQl API Jul 08, 2025 am 01:03 AM

要構(gòu)建一個(gè)GraphQLAPI在Go語(yǔ)言中,推薦使用gqlgen庫(kù)以提高開(kāi)發(fā)效率。 1.首先選擇合適的庫(kù),如gqlgen,它支持根據(jù)schema自動(dòng)生成代碼;2.接著定義GraphQLschema,描述API的結(jié)構(gòu)和查詢(xún)?nèi)肟?,如定義Post類(lèi)型和查詢(xún)方法;3.然後初始化項(xiàng)目並生成基礎(chǔ)代碼,實(shí)現(xiàn)resolver中的業(yè)務(wù)邏輯;4.最後將GraphQLhandler接入HTTPserver,通過(guò)內(nèi)置Playground測(cè)試API。注意事項(xiàng)包括字段命名規(guī)範(fàn)、錯(cuò)誤處理、性能優(yōu)化及安全設(shè)置等,確保項(xiàng)目可維護(hù)性

如何安裝去 如何安裝去 Jul 09, 2025 am 02:37 AM

安裝Go的關(guān)鍵在於選擇正確版本、配置環(huán)境變量並驗(yàn)證安裝。 1.前往官網(wǎng)下載對(duì)應(yīng)系統(tǒng)的安裝包,Windows使用.msi文件,macOS使用.pkg文件,Linux使用.tar.gz文件並解壓至/usr/local目錄;2.配置環(huán)境變量,在Linux/macOS中編輯~/.bashrc或~/.zshrc添加PATH和GOPATH,Windows則在系統(tǒng)屬性中設(shè)置PATH為Go的安裝路徑;3.使用goversion命令驗(yàn)證安裝,並運(yùn)行測(cè)試程序hello.go確認(rèn)編譯執(zhí)行正常。整個(gè)流程中PATH設(shè)置和環(huán)

Go Sync.WaitGroup示例 Go Sync.WaitGroup示例 Jul 09, 2025 am 01:48 AM

sync.WaitGroup用於等待一組goroutine完成任務(wù),其核心是通過(guò)Add、Done、Wait三個(gè)方法協(xié)同工作。 1.Add(n)設(shè)置需等待的goroutine數(shù)量;2.Done()在每個(gè)goroutine結(jié)束時(shí)調(diào)用,計(jì)數(shù)減一;3.Wait()阻塞主協(xié)程直到所有任務(wù)完成。使用時(shí)需注意:Add應(yīng)在goroutine外調(diào)用、避免重複Wait、務(wù)必確保Done被調(diào)用,推薦配合defer使用。常見(jiàn)於並發(fā)抓取網(wǎng)頁(yè)、批量數(shù)據(jù)處理等場(chǎng)景,能有效控制並發(fā)流程。

去嵌入軟件包教程 去嵌入軟件包教程 Jul 09, 2025 am 02:46 AM

使用Go的embed包可以方便地將靜態(tài)資源嵌入二進(jìn)制,適合Web服務(wù)打包HTML、CSS、圖片等文件。 1.聲明嵌入資源需在變量前加//go:embed註釋?zhuān)缜度雴蝹€(gè)文件hello.txt;2.可嵌入整個(gè)目錄如static/*,通過(guò)embed.FS實(shí)現(xiàn)多文件打包;3.開(kāi)發(fā)時(shí)建議通過(guò)buildtag或環(huán)境變量切換磁盤(pán)加載模式以提高效率;4.注意路徑正確性、文件大小限制及嵌入資源的只讀特性。合理使用embed能簡(jiǎn)化部署並優(yōu)化項(xiàng)目結(jié)構(gòu)。

進(jìn)行音頻/視頻處理 進(jìn)行音頻/視頻處理 Jul 20, 2025 am 04:14 AM

音視頻處理的核心在於理解基本流程與優(yōu)化方法。 1.其基本流程包括採(cǎi)集、編碼、傳輸、解碼和播放,每個(gè)環(huán)節(jié)均有技術(shù)難點(diǎn);2.常見(jiàn)問(wèn)題如音畫(huà)不同步、卡頓延遲、聲音噪音、畫(huà)面模糊等,可通過(guò)同步調(diào)整、編碼優(yōu)化、降噪模塊、參數(shù)調(diào)節(jié)等方式解決;3.推薦使用FFmpeg、OpenCV、WebRTC、GStreamer等工具實(shí)現(xiàn)功能;4.性能管理方面應(yīng)注重硬件加速、合理設(shè)置分辨率幀率、控制並發(fā)及內(nèi)存洩漏問(wèn)題。掌握這些關(guān)鍵點(diǎn)有助於提升開(kāi)發(fā)效率和用戶(hù)體驗(yàn)。

如何在GO中構(gòu)建Web服務(wù)器 如何在GO中構(gòu)建Web服務(wù)器 Jul 15, 2025 am 03:05 AM

搭建一個(gè)用Go編寫(xiě)的Web服務(wù)器並不難,核心在於利用net/http包實(shí)現(xiàn)基礎(chǔ)服務(wù)。 1.使用net/http啟動(dòng)最簡(jiǎn)服務(wù)器:通過(guò)幾行代碼註冊(cè)處理函數(shù)並監(jiān)聽(tīng)端口;2.路由管理:使用ServeMux組織多個(gè)接口路徑,便於結(jié)構(gòu)化管理;3.常見(jiàn)做法:按功能模塊分組路由,並可用第三方庫(kù)支持複雜匹配;4.靜態(tài)文件服務(wù):通過(guò)http.FileServer提供HTML、CSS和JS文件;5.性能與安全:?jiǎn)⒂肏TTPS、限制請(qǐng)求體大小、設(shè)置超時(shí)時(shí)間以提升安全性與性能。掌握這些要點(diǎn)後,擴(kuò)展功能將更加容易。

使用默認(rèn)情況選擇 使用默認(rèn)情況選擇 Jul 14, 2025 am 02:54 AM

select加default的作用是讓select在沒(méi)有其他分支就緒時(shí)執(zhí)行默認(rèn)行為,避免程序阻塞。 1.非阻塞地從channel接收數(shù)據(jù)時(shí),若channel為空,會(huì)直接進(jìn)入default分支;2.結(jié)合time.After或ticker定時(shí)嘗試發(fā)送數(shù)據(jù),若channel滿(mǎn)則不阻塞而跳過(guò);3.防止死鎖,在不確定channel是否被關(guān)閉時(shí)避免程序卡住;使用時(shí)需注意default分支會(huì)立即執(zhí)行,不能濫用,且default與case互斥,不會(huì)同時(shí)執(zhí)行。

See all articles