寫一個Go HTTP服務器
-
打開一個新的終端窗口,但讓守護進程運行的窗口離開。此窗口將用於運行UniK CLI命令。
-
使用文本編輯器創建文件httpd.go。將以下代碼複製並粘貼到該文件中:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "my first unikernel!")
}
- 嘗試運行此代碼
go run http.go
。訪問http:// localhost:8080 /看到服務器正在運行。 - 我們需要創建一個虛擬
Godeps
文件。告訴Go編譯器如何構建Go項目及其依賴關係是必要的。幸運的是,在這個例子中,我們的項目沒有依賴關係,我們可以在Godeps
沒有安裝的情況下填寫一個簡單的文件godep
。注意:對於具有導入依賴關係的Go項目和嵌套包,您將需要安裝Godeps並運行GO15VENDOREXPERIMENT=1 godep save ./...
在項目中。有關詳細信息,請參閱使用UniK編譯Go應用程序。
- 要創建虛擬Godeps文件,請創建
Godeps
與目錄相同的文件夾httpd.go
。在裏面,創建一個名爲Godeps.json
並粘貼以下內容的文件:
{
"ImportPath": "my_httpd",
"GoVersion": "go1.6",
"GodepVersion": "v63",
"Packages": [
"./.."
],
"Deps": [
{
"ImportPath": "github.com/cf-unik/unik/docs/examples",
"Rev": "f8cc0dd435de36377eac060c93481cc9f3ae9688"
}
]
}
- For the purposes of this example, that matters here is
my_httpd
. It instructs the go compiler that the project should be installed from$GOPATH/src/my_httpd
.
- Great! Now we're ready to compile this code to a unikernel.