2015-12-18

[Golang] 用Go (golang) 寫Web Server! 使用go-restful package. Hello go-restful!

1. 安裝go
https://golang.org/doc/install
https://golang.org/dl/

    *如果有安裝舊版的要先移除
    *Mac版的pkg只要抓下來執行一直按下一步就安裝好。
        他會幫你把go安裝在/usr/local/go,
        並把/usr/local/go/bin加到環境變數PATH當中。
        記得要把Terminal關掉重開才會吃到新的PATH。

2.  準備一個HelloWebServer的Workspace
        1. 新增一個資料夾當作這個程式的Workspace, ex. ~/HelloWebServer/
        2. 把這個folder path加入環境變數,
             ex. 執行 $ export GOPATH=$HOME/HelloWebServer
        3. 在work folder底下加入src/HelloWebServer/hellowebserver.go
            內容為

package main

import (
 "github.com/emicklei/go-restful"
 "io"
 "net/http"
)

// This example shows the minimal code needed to get a restful.WebService working.
//
// GET http://localhost:8080/hello

func main() {
 ws := new(restful.WebService)
 ws.Route(ws.GET("/hello").To(hello))
 restful.Add(ws)
 http.ListenAndServe(":8080", nil)
}

func hello(req *restful.Request, resp *restful.Response) {
 io.WriteString(resp, "world")
}

     

3. 執行$ go get github.com/emicklei/go-restful
    go會幫你把go-restful的檔案抓下來到Workspace裡面的src底下。

4. 執行$ go install HelloWebServer
     這會在work folder底下產生一個bin\HelloWebServer執行檔
     
5. 執行$GOPATH/bin/HelloWebServer
     這樣web server就開始執行了!

6. 打開瀏覽器,在網址列輸入http://localhost:8080/hello
     如果網頁出現了world就是成功囉!

7. 要將hellowebserver程式關掉的話,只要用鍵盤輸入control+C就可以了。
    用Mac的話也是輸入control+C就可以結束程式,不是command+C喔!