日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

在IIS上部署Go?API項(xiàng)目_win服務(wù)器

作者:taadis ? 更新時(shí)間: 2022-10-25 編程語言

問題場景

我這邊原先的技術(shù)棧主要是 .NET(Core), 所以服務(wù)器基本上都是 Windows Server + IIS.

這次有個(gè) API 服務(wù)用 Go 重寫, 但是部署有點(diǎn)不美, 直接執(zhí)行黑框框不好看, 也容易丟, 做成服務(wù)又不方便更新維護(hù), 想著能不能繼續(xù)掛載在 IIS 下.

于是乎...

首先想到的是 IIS 下有個(gè) FastCGI 支持, 以前還在 IIS 下部署過 PHP 項(xiàng)目.

搜到 Go 中有個(gè)?net/http/fcgi?庫, 寫個(gè)簡單服務(wù)驗(yàn)證一下, 代碼如下:

package main

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

func handler(resp http.ResponseWriter, req *http.Request) {
	resp.Write([]byte("hello"))
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", handler)

	l, err := net.Listen("tcp", ":0")
	if err != nil{
		panic(err)
	}
	err = fcgi.Serve(l, mux)
	if err != nil{
		panic(err)
	}
}

執(zhí)行?go run main.go?命令后, 程序沒有任何異常或輸出直接就結(jié)束了...

資料搜了一圈看到這玩意基本已被遺忘在不知道哪個(gè)旮旯里了...

然后搜到 Azure 前些年用 HttpPlatformHandler Module 在 IIS 上支持 Java/Node/... 應(yīng)用程序.

試了下基本也是廢了.

解決方案

最后溜達(dá)了一圈, 發(fā)現(xiàn) HttpPlatformHandler 已被 ASPNETCore Module 宿主模塊取代.

那么就跟我們在 IIS 上部署 ASP.NET Core 應(yīng)用程序一樣, 首先下載并安裝?ASP.NET Core Hosting Bundle, 了解更多可參閱?ASP.NET Core Module

然后新建對應(yīng)的站點(diǎn), 應(yīng)用程序池調(diào)整成?無托管代碼

IIS 這邊已經(jīng)準(zhǔn)備就緒.

來看看我們代碼和配置

// main.go
package main

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

func handler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Go running on IIS"))
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", handler)

	// 獲取由 ACNM 設(shè)置的環(huán)境變量
	port := "0" // default
	envPort := os.Getenv("ASPNETCORE_PORT")
	if envPort != "" {
		port = envPort
		fmt.Println("get env ASPNETCORE_PORT", port)
	}

	l, err := net.Listen("tcp", ":" + port)
	if err != nil{
		panic(err)
	}
	defer l.Close()
	fmt.Println("listening on", l.Addr().String())
	err = http.Serve(l, mux)
	if err != nil{
		panic(err)
	}
}

關(guān)鍵點(diǎn)就是代碼中要通過獲取 ACNM 提供的端口環(huán)境變量, 也就是?ASPNETCORE_PORT, 熟悉 ASP.NET Core 的小伙伴對這個(gè)應(yīng)該不陌生了.

然后構(gòu)建我們的可執(zhí)行文件 xxx.exe

go build

然后配置 web.config 內(nèi)容如下:

<!-- web.config -->
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath=".\your.exe" arguments="" stdoutLogEnabled="true" stdoutLogFile=".\stdout" />
    </system.webServer>
  </location>
</configuration>

把?xxx.exe?和?web.config?扔到前面新建的站點(diǎn)中即可.

后續(xù)更新升級直接替換 exe 即可.

Go 寫的程序體積比較小, 構(gòu)建后也只有單個(gè)執(zhí)行文件, 清爽多了.

最后來個(gè)效果圖

注意事項(xiàng)

如出現(xiàn)以下錯(cuò)誤信息, 可能是端口號已被占用, 換個(gè)端口號試試

[ERROR] listen tcp :8080: bind: An attempt was made to access a socket in a way forbidden by its access permissions.

原文鏈接:https://www.cnblogs.com/taadis/p/how-to-deploy-go-api-on-iis.html

欄目分類
最近更新