練習 - 使用自訂處理常式建立應用程式
在此練習中,您將使用 Go 建置並執行無伺服器應用程式。
建構應用程式
請先使用 Visual Studio Code 中的 Azure Functions 延伸模組建構應用程式。
- 選取 [檢視]>[命令選擇區]。
- 選取 [Azure Functions: 建立新專案]。
- 選取資料夾,通常是您目前的資料夾。
- 在 [選取語言] 中,選取 [自訂處理常式]。
- 在 [Select a template for your first function] (為您的第一個函式選取範本) 中,選取 [HttpTrigger]。
- 提供應用程式的名稱,例如 hello。
- 選取 [匿名] 的授權等級。 您稍後可以視需要變更該設定。
現在您的專案看起來像這樣:
hello/
function.json
.funcignore
.gitignore
host.json
local.settings.json
proxies.json
建立 應用程式
下一組連續步驟與建立可回應 HTTP 觸發程序的應用程式有關。
在專案根目錄中建立名為 server.go 的檔案。
為 server.go 提供下列內容:
package main import ( "fmt" "io" "log" "net/http" "os" )上述程式碼會匯入建置 HTTP 應用程式和查詢環境變數所需的所有程式庫。
在匯入陳述式後面新增下列程式碼:
func main() { customHandlerPort, exists := os.LookupEnv("FUNCTIONS_CUSTOMHANDLER_PORT") if !exists { customHandlerPort = "8080" } mux := http.NewServeMux() // mux.HandleFunc("/api/hello", helloHandler) fmt.Println("Go server Listening on: ", customHandlerPort) log.Fatal(http.ListenAndServe(":"+customHandlerPort, mux)) }main()函式是由其本身所叫用。 程式碼的第一行指出要如何從FUNCTIONS_CUSTOM_HANDLER_PORT環境變數讀取:customHandlerPort, exists := os.LookupEnv("FUNCTIONS_CUSTOMHANDLER_PORT")接下來,函式會檢查連接埠是否存在。 如果不是這樣,則會將函式分配到連接埠 8080:
if !exists { customHandlerPort = "8080" }下一行程式碼會將 HTTP 伺服器執行個體具現化:
mux := http.NewServeMux()最後很重要的一行會使用
ListenAndServe()方法開始接聽特定連接埠,並發出訊號指出已準備好接收要求:log.Fatal(http.ListenAndServe(":"+customHandlerPort, mux))讓我們新增其餘程式碼。 首先,將下一行當地語系化並取消註解:
// mux.HandleFunc("/api/hello", helloHandler)在匯入陳述式與
main()函式之間,新增下列程式碼:func helloHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") if r.Method == "GET" { w.Write([]byte("hello world")) } else { body, _ := io.ReadAll(r.Body) w.Write(body) } }helloHandler()函式會將內容類型設定為application/json。 其會以 "hello world" 或張貼的本文 (如果有的話) 回應。
執行應用程式
此時您已完成撰寫程式碼,但您必須進行一些設定,才能讓此情節運作正常。 您必須指出可執行檔的位置,讓 Function 主機可以找到。 您也必須設定路由,並指出此應用程式處理的是 HTTP 觸發程序,而不是其他類型的繫結。
從終端,在專案根目錄中執行
go build server.go:go build server.go此步驟會建立名為 server (macOS 和 Linux 上) 或 server.exe (Windows OS 上) 的可執行檔。
開啟 host.json 檔案,並尋找
defaultExecutablePath中的customHandler元素。 指定./server(macOS 和 Linux 上) 或.\\server.exe(Windows OS 上)。在
customHandler元素下,新增enableForwardingHttpRequest元素並為其指定值true。 您的customHandler元素現在看起來應該像這樣:"customHandler": { "description": { "defaultExecutablePath": "./server", "workingDirectory": "", "arguments": [] }, "enableForwardingHttpRequest" : true }從終端,在專案根目錄中執行
func start。 這麼做會啟動您的 Functions 應用程式。func start在輸出的結尾,您會看到類似如下的輸出:
Functions: hello: [GET,POST] http://localhost:7071/api/hello在瀏覽器中,前往
http://localhost:7071/api/hello。 您應該會看到以下輸出:"hello world"。
恭喜! 您已在 Go 中開發無伺服器應用程式。