mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-11-13 09:16:10 +08:00
@@ -4,7 +4,7 @@
|
||||
|
||||
当开始一个新项目或增加新的功能到现有的项目,你可以通过在应用程序中使用已经存在的库来节省开发时间。为了做到这一点,你必须理解库的 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 的 urlshortener 编写一个小程序:你可以尝试一下在 http://goo.gl/ 输入一个像 "http://www.destandaard.be" 这样的 URL,你会看到一个像 "http://goo.gl/O9SUO" 这样更短的 URL 返回,也就是说,在 Twitter 之类的服务中这是非常容易嵌入的。谷歌 urlshortener 服务的文档可以在 "http://code.google.com/apis/urlshortener/" 找到。([第 19 章](19.0.md),我们将开发自己版本的 urlshortener)。
|
||||
|
||||
谷歌将这项技术提供给其他开发者,我们可以在我们自己的应用程序中调用 API (释放到指定的限制)。他们也生成了一个 Go 语言客户端库使调用变得更容易。
|
||||
|
||||
@@ -24,9 +24,9 @@ go install 将下载源码,编译并安装包
|
||||
|
||||
import "google.golang.org/api/urlshortener/v1"
|
||||
|
||||
现在我们写一个 Web 应用(参见第 15 章 4-8 节)通过表单实现短地址和长地址的相互转换。我们将使用 `template` 包并写三个处理函数:root 函数通过执行表单模板来展示表单,short 函数将长地址转换为短地址,long 函数逆向转换。
|
||||
现在我们写一个 Web 应用(参见[第 15 章 4-8 节](15.4.md))通过表单实现短地址和长地址的相互转换。我们将使用 `template` 包并写三个处理函数:`root()` 函数通过执行表单模板来展示表单,`short()` 函数将长地址转换为短地址,`long()` 函数逆向转换。
|
||||
|
||||
要调用 urlshortener 接口必须先通过 http 包中的默认客户端创建一个服务实例 urlshortenerSvc:
|
||||
要调用 `urlshortener` 接口必须先通过 `http` 包中的默认客户端创建一个服务实例 `urlshortenerSvc`:
|
||||
```go
|
||||
urlshortenerSvc, _ := urlshortener.New(http.DefaultClient)
|
||||
```
|
||||
@@ -47,7 +47,7 @@ url, error := urlshortenerSvc.Url.Get(shwortUrl).Do()
|
||||
|
||||
返回的长地址便是转换前的原始地址。
|
||||
|
||||
示例 9.9 [urlshortener.go](examples/chapter_9/use_urlshortener.go)
|
||||
示例 9.9 [urlshortener.go](examples/chapter_9/use_urlshortener.go)
|
||||
|
||||
```go
|
||||
package main
|
||||
@@ -146,4 +146,5 @@ script: _go_app
|
||||
|
||||
- [目录](directory.md)
|
||||
- 上一节:[Go 的外部包和项目](09.10.md)
|
||||
- 下一章:[结构(struct)与方法(method)](10.0.md)
|
||||
- 下一章:[结构 (struct) 与方法 (method)](10.0.md)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user