windows 解决 go包 endless 报错:undefined:syscall.SIGUSR1、undefined: syscall.SIGUSR2、undefined:syscall.SIGUSR1、undefined: syscall.SIGTSTP

前言

在使用 github.com/fvbock/endless 时,windows 平台报错:

原因

github.com/fvbock/endless 这个库用到了相关 syscall.SIGUSR1syscall.SIGUSR2 信号,这些信号是 Unix/Linux 下的用户自定义信号,Windows 平台没有这些信号,所以在 Windows 下编译 Go 项目会报 undefined

解决

Windows 下用标准库 http.ServerLinux 下用 endless 实现热重启,可以用 Go 的条件编译(build tag)机制实现平台差异。

可以看看我这篇博客:go 编译约束//go:build dev //+build

步骤一:拆分文件

假设你的项目结构如下:

server/
  runserver_endless.go
  runserver_std.go
  routers.go
  ...

步骤二:分别写两个实现

1. Linux/Unix(用 endless)

server/runserver_endless.go:

//go:build !windows
// +build !windows

package server

import (
	"fmt"
	"time"
	"github.com/fvbock/endless"
	"go.uber.org/zap"

	"algo-warehouse/control-server/internal/common/global"
)

func RunServer() {
	router := routers()
	address := fmt.Sprintf(":%d", global.CONFIG.System.Addr)

	s := endless.NewServer(address, router)
	s.ReadHeaderTimeout = 20 * time.Second
	s.WriteTimeout = 20 * time.Second
	s.MaxHeaderBytes = 1 << 20

	fmt.Println(fmt.Sprintf("默认文档地址:http://127.0.0.1%s/swagger/index.html", address))
	global.LOG.Info("server run success on ", zap.String("address", address))
	global.LOG.Error(s.ListenAndServe().Error())
}

2. Windows(用标准库)

server/runserver_std.go:

//go:build !windows
// +build !windows

package server

import (
	"fmt"
	"time"
	"github.com/fvbock/endless"
	"go.uber.org/zap"

	"algo-warehouse/control-server/internal/common/global"
)

func RunServer() {
	router := routers()
	address := fmt.Sprintf(":%d", global.CONFIG.System.Addr)

	s := endless.NewServer(address, router)
	s.ReadHeaderTimeout = 20 * time.Second
	s.WriteTimeout = 20 * time.Second
	s.MaxHeaderBytes = 1 << 20

	fmt.Println(fmt.Sprintf("默认文档地址:http://127.0.0.1%s/swagger/index.html", address))
	global.LOG.Info("server run success on ", zap.String("address", address))
	global.LOG.Error(s.ListenAndServe().Error())
}

步骤三:保持调用不变

你在其他地方,只需要调用:

server.RunServer()

编译时,Go 会自动选择对应平台的实现。

posted @ 2025-04-22 17:46  牛奔  阅读(231)  评论(0)    收藏  举报