Using external libraries in Go programs

When starting a new project or adding new functions to an existing project, you can save development time by using existing libraries in your application. In order to do this, you must understand the API (Application Programming Interface) of the library, that is: what methods can be called in the library and how to call them. You may not have the source code of this library, but the author must have documented the API and detailed how to use it.

As an example, we will write a small program using urlshorter of Google's API: you can try it in goo.gl/ Enter an image“ www.destandaard.be "Such a URL, you will see a url like" goo.gl/O9SUO "Such a shorter URL return, that is, it is very easy to embed in services such as Twitter. The documents of Google urlshorter service can be found in" code.google.com/apis/urlshortener/ "Found.

Google provides this technology to other developers. As API, we can call it in our own application (release to specified limits). They also generated a Go language client library to make it easier.

Note: Google makes the life of developers who use Google API Go client service easier. The Go client program is automatically generated in the JSON description of Google Library. More details are available at Project page see.

Download and install the Go Client Library:

It will be implemented through go install. However, first verify whether the environment variable contains GOPATH variable, because the external source code will be downloaded to the $GOPATH/src directory and installed in the $GOPATH/PKG/"machine_arch" / directory.

We will install the API by calling the following command on the terminal:

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

go install will download the source code, compile and install the package

web application using urlshorter service:

Now we can use the installed package by importing and aliasing it:

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

Now let's write a Web application to realize the mutual conversion of short address and long address through a form. We will use the template package and write three processing functions: the root function displays the form by executing the form template. The short function converts a long address into a short address, and the long function reverses the conversion.

To call the urlshortener interface, you must first create a service instance urlshortenerSvc through the default client in the http package:

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

We call the Url in the service The Do method in insert passes in the Url data structure containing the long address to obtain the short address:

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

The Id of the returned url is the short address we need.

We call the Url in the service The Do method in get passes in the Url data structure containing the short address to obtain the long address:

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

The returned long address is the original address before conversion.

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))
}

Execute this Code:

go run urlshortener.go

By browsing http://localhost:8080/ Page to test.

For the sake of code simplicity, we do not detect the returned error status, but we must do it in the application of real production environment.

To put the application into Google App Engine, we only need to make the following changes in the previous code:

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

Create a directory urlshort with the same name as the package, and copy the following two installation directories to this directory:

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

In addition, configure the configuration file app Yaml, as follows:

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

Now you can go to your project directory and run it on the terminal: dev_appserver.py urlshort

Open your Web app in a browser: localhost:8080.

Added by tili on Fri, 04 Feb 2022 08:37:02 +0200