9.11 在 Go 程序中使用外部庫

(本節我們將創建一個 Web 應用和它的 Google App Engine 版本,在第 19 和 21 章分別說明,當你閱讀到這些章節時可以再回到這個例子。)

當開始一個新項目或增加新的功能到現有的項目,你可以通過在應用程序中使用已經存在的庫來節省開發時間。爲了做到這一點,你必須理解庫的 API(應用編程接口),那就是:庫中有哪些方法可以調用,如何調用。你可能沒有這個庫的源代碼,但作者肯定有記載的 API 以及詳細介紹瞭如何使用它。

作爲一個例子,我們將使用谷歌的 API 的 urlshortener 編寫一個小程序:你可以嘗試一下在 http://goo.gl/ 輸入一個像 "http://www.destandaard.be" 這樣的URL,你會看到一個像 "http://goo.gl/O9SUO" 這樣更短的 URL 返回,也就是說,在 Twitter 之類的服務中這是非常容易嵌入的。谷歌 urlshortener 服務的文檔可以在 "http://code.google.com/apis/urlshortener/" 找到。(第 19 章,我們將開發自己版本的 urlshortener)。

谷歌將這項技術提供給其他開發者,作爲 API 我們可以在我們自己的應用程序中調用(釋放到指定的限制。他們也生成了一個 Go 語言客戶端庫使其變得更容易。

備註:谷歌讓通過使用 Google API Go 客戶端服務的開發者生活變得更簡單,Go 客戶端程序自動生成於 Google 庫的 JSON 描述。更多詳情在 項目頁面 查看。

下載並安裝 Go 客戶端庫: 將通過 go install 實現。但是首先要驗證環境變量中是否含有 GOPATH 變量,因爲外部源碼將被下載到 $GOPATH/src 目錄下並被安裝到 $GOPATH/PKG/"machine_arch"/ 目錄下。

我們將通過在終端調用以下命令來安裝 API:

go install google-api-go-client.google.com/hg/urlshortener/v1

go install 將下載源碼,編譯並安裝包

使用 urlshortener 服務的 web 程序: 現在我們可以通過導入並賦予別名來使用已安裝的包:

`import urlshortener "google-api-go-client.googlecode.com/hg/urlshortener/v1"`

現在我們寫一個 Web 應用(參見第 15 章 4-8 節)通過表單實現短地址和長地址的相互轉換。我們將使用 template 包並寫三個處理函數:root 函數通過執行表單模板來展示表單。short 函數將長地址轉換爲短地址,long 函數逆向轉換。

要調用 urlshortener 接口必須先通過 http 包中的默認客戶端創建一個服務實例 urlshortenerSvc:

urlshortenerSvc, _ := urlshortener.New(http.DefaultClient)

我們通過調用服務中的 Url.Insert 中的 Do 方法傳入包含長地址的 Url 數據結構從而獲取短地址:

url, _ := urlshortenerSvc.Url.Insert(&urlshortener.Url{LongUrl: longUrl}).Do()

返回 urlId 便是我們需要的短地址。

我們通過調用服務中的 Url.Get 中的 Do 方法傳入包含短地址的Url數據結構從而獲取長地址:

url, error := urlshortenerSvc.Url.Get(shwortUrl).Do()

返回的長地址便是轉換前的原始地址。

示例 9.9 urlshortener.go

package main

import (
     "fmt"
     "net/http"
     "text/template"

     urlshortener "google-api-go-client.googlecode.com/hg/urlshortener/v1"
)
func main() {
     http.HandleFunc("/", root)
     http.HandleFunc("/short", short)
     http.HandleFunc("/long", long)

     http.ListenAndServe("localhost:8080", nil)
}
// the template used to show the forms and the results web page to the user
var rootHtmlTmpl = template.Must(template.New("rootHtml").Parse(`
<html><body>
<h1>URL SHORTENER</h1>
{{if .}}{{.}}<br /><br />{{end}}
<form action="/short" type="POST">
Shorten this: <input type="text" name="longUrl" />
<input type="submit" value="Give me the short URL" />
</form>
<br />
<form action="/long" type="POST">
Expand this: http://goo.gl/<input type="text" name="shortUrl" />
<input type="submit" value="Give me the long URL" />
</form>
</body></html>
`))
func root(w http.ResponseWriter, r *http.Request) {
    rootHtmlTmpl.Execute(w, nil)
}
func short(w http.ResponseWriter, r *http.Request) {
     longUrl := r.FormValue("longUrl")
     urlshortenerSvc, _ := urlshortener.New(http.DefaultClient)
     url, _ := urlshortenerSvc.Url.Insert(&urlshortener.Url{LongUrl:
     longUrl,}).Do()
     rootHtmlTmpl.Execute(w, fmt.Sprintf("Shortened version of %s is : %s",
     longUrl, url.Id))
}

func long(w http.ResponseWriter, r *http.Request) {
     shortUrl := "http://goo.gl/" + r.FormValue("shortUrl")
     urlshortenerSvc, _ := urlshortener.New(http.DefaultClient)
     url, err := urlshortenerSvc.Url.Get(shortUrl).Do()
     if err != nil {
         fmt.Println("error: %v", err)
         return

     }
     rootHtmlTmpl.Execute(w, fmt.Sprintf("Longer version of %s is : %s",
     shortUrl, url.LongUrl))
}

執行這段代碼:

go run urlshortener.go

通過瀏覽 http://localhost:8080/ 的頁面來測試。

爲了代碼的簡潔我們並沒有檢測返回的錯誤狀態,但是在真實的生產環境的應用中一定要做檢測。

將應用放入Google App Engine,我們只需要在之前的代碼中作出如下改變:

package main -> package urlshort
func main() -> func init()

創建一個和包同名的目錄 urlshort,並將以下兩個安裝目錄複製到這個目錄:

google-api-go-client.googlecode.com/hg/urlshortener
google-api-go-client.googlecode.com/hg/google-api

此外還要配置下配置文件 app.yaml,內容如下:

application: urlshort
version: 0-1-test
runtime: go
api_version: 3
handlers:
- url: /.*
script: _go_app

現在你可以去到你的項目目錄並在終端運行:dev_appserver.py urlshort

在瀏覽器打開你的 Web應用:http://localhost:8080。

鏈接

results matching ""

    No results matching ""