ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

在 Go 程序中使用外部库

2022-02-04 14:32:36  阅读:154  来源: 互联网

标签:google http Url 外部 程序 go url Go urlshortener


当开始一个新项目或增加新的功能到现有的项目,你可以通过在应用程序中使用已经存在的库来节省开发时间。为了做到这一点,你必须理解库的 API(应用编程接口),那就是:库中有哪些方法可以调用,如何调用。你可能没有这个库的源代码,但作者肯定有记载的 API 以及详细介绍了如何使用它。

  作为一个例子,我们将使用谷歌的 API 的 urlshortener 编写一个小程序:你可以尝试一下在 goo.gl/ 输入一个像 "www.destandaard.be"这样的 URL,你会看到一个像"goo.gl/O9SUO"这样更短的 URL 返回,也就是说,在 Twitter 之类的服务中这是非常容易嵌入的。谷歌 urlshortener 服务的文档可以在"code.google.com/apis/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 应用通过表单实现短地址和长地址的相互转换。我们将使用 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()

  返回的长地址便是转换前的原始地址。

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 应用:localhost:8080

标签:google,http,Url,外部,程序,go,url,Go,urlshortener
来源: https://www.cnblogs.com/galaxies2580/p/15862796.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有