mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-11 19:41:43 +08:00
9.10
This commit is contained in:
@@ -9,7 +9,7 @@
|
||||
|
||||
## 翻译进度
|
||||
|
||||
9.9 [通过 git 打包和安装](eBook/09.9.md)
|
||||
9.10 [Go 的外部包和项目](eBook/09.10.md)
|
||||
|
||||
## 支持本书
|
||||
|
||||
|
BIN
eBook/09.10.md
BIN
eBook/09.10.md
Binary file not shown.
@@ -1,4 +1,6 @@
|
||||
#9.11 在Go程序中使用外部库
|
||||
# 9.11 在 Go 程序中使用外部库
|
||||
|
||||
219
|
||||
(本节我们将创建一个web应用和它的Google App Engine版本,在第19和21章分别说明,当你阅读到这些章节时可以再回到这个例子。)
|
||||
|
||||
当开始一个新项目或增加新的功能到现有的项目,你可以通过在应用程序中使用已经存在的库来节省开发时间。为了做到这一点,你必须理解库的API(应用编程接口),那就是:库中有哪些方法可以调用,如何调用。你可能没有这个库的源代码,但作者肯定有记载的API以及详细介绍了如何使用它。
|
||||
@@ -13,7 +15,7 @@
|
||||
将通过go install实现。但是首先要验证环境变量中是否含有GOPATH变量,因为外部源码将被下载到$GOPATH/src目录下并被安装到$GOPATH/PKG/"machine_arch"/目录下。
|
||||
|
||||
我们将通过在终端调用以下命令来安装API:
|
||||
|
||||
|
||||
go install google-api-go-client.google.com/hg/urlshortener/v1
|
||||
|
||||
go install将下载源码,编译并安装包
|
||||
@@ -26,25 +28,25 @@ go install将下载源码,编译并安装包
|
||||
现在我们写一个web应用(参见第十五章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()
|
||||
|
||||
|
||||
返回url的Id便是我们需要的短地址。
|
||||
|
||||
我们通过调用服务中的Url.Get中的Do方法传入包含短地址的Url数据结构从而获取长地址:
|
||||
|
||||
|
||||
url, error := urlshortenerSvc.Url.Get(shwortUrl).Do()
|
||||
|
||||
|
||||
返回的长地址便是转换前的原始地址。
|
||||
|
||||
实例 9.9 [urlshortener.go](examples/chapter_9/urlshortener.go)
|
||||
|
||||
package main
|
||||
import (
|
||||
package main
|
||||
import (
|
||||
“fmt”
|
||||
“net/http”
|
||||
“text/template”
|
||||
@@ -59,4 +61,4 @@ go install将下载源码,编译并安装包
|
||||
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(`
|
||||
var rootHtmlTmpl = template.Must(template.New(“rootHtml”).Parse(`
|
||||
|
@@ -83,6 +83,7 @@
|
||||
- 9.8 [自定义包的目录结构、go install 和 go test](09.8.md)
|
||||
- 9.9 [通过 git 打包和安装](09.9.md)
|
||||
- 9.10 [Go 的外部包和项目](09.10.md)
|
||||
- 9.11 [在 Go 程序中使用外部库](09.11.md)
|
||||
- 第10章:结构(struct)与方法(method)
|
||||
- 第11章:接口(interface)与反射(reflection)
|
||||
|
||||
|
Reference in New Issue
Block a user