在Windows 11的IIS 10上部署Golang可执行文件

在Windows 11的IIS 10上部署Golang可执行文件 谁能详细说明一下将Go可执行文件部署到IIS 10的过程?

4 回复

实际上,我开发了一些API,需要部署在一台Windows服务器上,以便前端团队能够访问它们。

更多关于在Windows 11的IIS 10上部署Golang可执行文件的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


创建 Golang Gin REST API 可执行文件并部署到指定端口。

创建 Web 前端并调用 REST API。

前端部署在 IIS 上。

抱歉,我不太理解这个问题。Go 的可执行文件是可以在操作系统上独立运行的应用程序。您需要与 IIS 进行哪种集成?反向代理吗?

通过搜索,我找到了几篇文章,但我从未在 IIS 上尝试过。

在Windows 11的IIS 10上部署Go可执行文件,需要通过FastCGI模块实现。以下是具体步骤:

1. 安装IIS和FastCGI模块

首先确保IIS已安装并启用FastCGI功能:

# 安装IIS和FastCGI
Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerRole
Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServer
Enable-WindowsOptionalFeature -Online -FeatureName IIS-CommonHttpFeatures
Enable-WindowsOptionalFeature -Online -FeatureName IIS-CGI

2. 编译Go程序为Windows可执行文件

# 交叉编译为Windows 64位可执行文件
GOOS=windows GOARCH=amd64 go build -o myapp.exe main.go

3. 配置FastCGI处理程序映射

在IIS管理器中:

  • 选择网站或应用程序
  • 打开"处理程序映射"
  • 添加模块映射:
    • 请求路径:*.go
    • 模块:FastCgiModule
    • 可执行文件:C:\path\to\your\myapp.exe
    • 名称:Go FastCGI

4. 配置web.config文件

在网站根目录创建或修改web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="GoHandler" 
                 path="*.go" 
                 verb="*" 
                 modules="FastCgiModule"
                 scriptProcessor="C:\apps\myapp.exe" 
                 resourceType="Unspecified" />
        </handlers>
        <fastCgi>
            <application fullPath="C:\apps\myapp.exe" 
                        arguments="" 
                        maxInstances="10" 
                        idleTimeout="300" 
                        activityTimeout="30" 
                        requestTimeout="90" 
                        instanceMaxRequests="10000">
                <environmentVariables>
                    <environmentVariable name="GOROOT" value="C:\Go" />
                    <environmentVariable name="GOPATH" value="C:\Go\Projects" />
                </environmentVariables>
            </application>
        </fastCgi>
    </system.webServer>
</configuration>

5. Go程序需要实现FastCGI接口

package main

import (
    "fmt"
    "net/http"
    "net/http/fcgi"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Go application running on IIS via FastCGI\n")
    fmt.Fprintf(w, "Request URL: %s\n", r.URL.Path)
}

func main() {
    http.HandleFunc("/", handler)
    // 监听FastCGI连接
    fcgi.Serve(nil, nil)
}

6. 设置应用程序池

  • 创建新的应用程序池,.NET CLR版本设置为"无托管代码"
  • 标识使用LocalSystem或自定义账户
  • 启用32位应用程序(如果Go程序是32位编译)

7. 权限配置

# 授予IIS用户对可执行文件的读取执行权限
icacls "C:\apps\myapp.exe" /grant "IIS_IUSRS:(RX)"

8. 测试配置

创建测试文件test.go(内容任意),通过浏览器访问http://localhost/test.go,应该能看到Go程序的响应输出。

注意事项:

  • Go程序必须持续运行以处理FastCGI请求
  • 确保防火墙允许IIS进程的网络访问
  • 日志可以通过Go程序的日志输出功能实现,配置到指定文件

这种配置允许IIS将特定请求(如*.go)转发给Go可执行文件处理,实现Go应用在IIS上的托管运行。

回到顶部