We know that Golang is increasingly being developed by developers. The Go language can also be used to develop Ubuntu Scope. In today’s tutorial, we will detail how to develop our Scope using the GO language. This is a boon for many developers who are not familiar with C/C++. The language is relatively new to me, too. If you want to learn golang, I suggest you read “Go by Example”.

\

For more on Go Scope development, see the article “Go Scopes Development”.

\

IDE choice

For some reason, currently our Ubuntu SDK does not support Scope development for go. The good news is that we can use the Command Line to complete our development. As the saying goes, good sickle does not mistakenly cut firewood. A good tool can certainly help us develop faster and better. The editor I currently use is LiteIDE. This is to go language and design of the IDE, very simple and use, I suggest you try.

\

\

\

Installing the development environment

\

We must first install the Golang package and related packages:

\

$sudo apt-get install unity-scope-tool golang git bzr python3-scope-harness mercurial
Copy the code

\

In order to be able to produce the click packs we need for our phones, we have to install the packs we need in our ARMHF chroot. We enter the following commands on the command line to enter the Maintainance mode of chroot:

\

$click chroot - aarmhf-fubuntu-sdK-15.04maintCopy the code

\

Then follow these steps to install the required packages:

\

# apt-get install golang
# apt-get install golang-go-linux-arm
# apt-get install libaccounts-glib-dev:armhf
# apt-get install crossbuild-essential-armhf
# apt-get install libsignon-glib-dev:armhf
Copy the code

\

Apt-get install libaccounts-glib-dev:armhf

\

(click-ubuntu-sdk-15.04-armhf)root@liuxg:/home/liuxg# apt-get install libsignon-glib-dev: armhf-f Reading package lists... Done Building dependency tree Reading state information... Done Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The  following information may help to resolve the situation: The following packages have unmet dependencies: libsignon-glib-dev:armhf : Depends: libdbus-glib-1-dev:armhf but it is not going to be installed Depends: Libglib2.0-dev :armhf but it is not going to be installed E: Unable to correct problems, You have held broken packages. (click-ubuntu-sdk-15.04-armhf)root@liuxg:/home/liuxg# apt-get install Libglib2.0-dev: armhf-f Reading package Lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: Gir1.2 - FreeDesktop gir1.2-gdkpixbuf-2.0 gir1.2- rsvG-2.0 ICU - devTools libbz2-dev libcairo-script- Interpreter2 libcdt5 libcgraph6 libdjvulibre-dev libdjvulibre-text libdjvulibre21 libexif-dev libexpat1-dev libfftw3-double3 libfontconfig1-dev libfreetype6-dev libgraphviz-dev libgvc6 libgvpr2 libice-dev libicu-dev libilmbase-dev libilmbase6 libjasper-dev libjbig-dev libjpeg-dev libjpeg-turbo8-dev libjpeg8-dev liblcms2-dev liblqr-1-0 liblqr-1-0-dev liblzma-dev  libmagick++-6-headers libmagick++-6.q16-5 libmagickcore-6-arch-config libmagickcore-6-headers libmagickcore-6.q16-2 libmagickcore-6.q16-2-extra libmagickwand-6-headers libmagickwand-6.q16-2 libopenexr-dev libopenexr6 libpathplan4 libpcre3-dev libpcrecpp0 libpixman-1-dev libpng12-dev libpthread-stubs0-dev libsm-dev libtiff5-dev libtiffxx5 libwmf-dev Libwmf0.2-7 libx11-dev libxau-dev libxcb-render0-dev libxcb-shm0-dev libxcb1-dev libxdmcp-dev libxdot4 libxext-dev libxml2-dev libxrender-dev libxt-dev libxt6 x11proto-render-dev zlib1g-dev Use 'apt-get autoremove' to remove them. The following extra packages will be installed: libpcre3-dev:armhf libpcrecpp0:armhf Suggested packages: Libglib2.0 -doc:armhf The following packages will be REMOVED: Libcairo2 -dev libgdk-pixbuf2.0-dev libglib2.0-dev libmagick++-6.q16-dev libmagick++-dev libmagickcore-6.q16-dev libmagickcore-6.q16-dev libmagickcore-6.q16-dev libmagickcore-6.q16-dev libmagickcore-6.q16 libmagickwand-6.q16-dev librsvg2-dev libzbar-dev:armhf The following NEW packages will be installed: Libglib2.0-dev :armhf libpcre3-dev:armhf libpcrecpp0:armhf 0 Upgrade, 3 newly installed, 9 to remove and 0 not upgraded. Need to get 1598 kB of archives. After this operation, 14.0MB Disk space will be freed. Do you want to continue? [Y/n] Y Get: 1 http://ports.ubuntu.com/ubuntu-ports/ vivid - updates/main libpcrecpp0 armhf 2:8. 35-3.3 ubuntu1.1 [13.4 kB] The Get: 2 http://ports.ubuntu.com/ubuntu-ports/ vivid - updates/main libpcre3 - dev armhf 2:8. 35-3.3 ubuntu1.1 [314 kB] Get: 3 http://ports.ubuntu.com/ubuntu-ports/ vivid - updates/main libglib2.0 - dev armhf 2.44.1-1 ubuntu1 [1270 kB] Fetched 1598 kB in 3s (433 kB/s) (Reading database ... 59571 files and directories directories currently installed.) Removing libzbar-dev (0.10+ doc-10BuilD1)...Copy the code

\

We can install the required packages with the “-f” option as shown above.

\

# apt-get install libglib2.0-dev:armhf -f
Copy the code

\

For the convenience of explaining the problem, you can download my template Scope: github.com/liu-xiao-gu…

\

Type the above command in your Terminal and you will find a directory called “goscope” in your directory:

\

liuxg@liuxg:~/release/goscope$ls -l total 68-rwxrwxr-x 1 liuxg liuxg 2886 7月 2 12:37 build-click-package.sh -rwxrwxr-x 1 liuxg LIUx752 7月 2 12:37 build. sh-rw-rw-x 1 liuxg LIUxg 1144 7月 2 12:37 clean. sh-rw-rw-r -- 1 liuxg LIUxg 9835 7月 2 12:37 goscope.gow-rw-r -- 1 liuxg LIUxg 329 7月 2 12:37 goscope.ini-RW-RW-r -- 1 liuxg LIUxg 102 7月 2 12:37 Goscope-security. Json -rw-rw-r-- 1 liuxg LIUxg 8403 7月 2 12:37 icon.jpg -RW-r -- 1 liuxg LIUxg 4851 7月 2 12:37 Logo.jpg-rw-rw-r -- 1 liuxg liuxg 435 7月 2 12:37 manifest.json -rwxrwxr-x 1 liuxg liuxg 1293 7月 2 12:37 run.sh -rwxrwxr-x 1 liuxg liuxg 1666 7月 2 12:37 setup-root -go.sh drwxrwxr-x 3 liuxg liux4096 7月 2 12:37 SRCCopy the code

From the above display, we can see that in addition to our expected GoScope.go file, we have several more scripts to help us with our work. To convert the downloaded script into an executable script, run the following command

\

$chmod +x *.sh
Copy the code

\

\

First, let’s take a look at our build.sh.

\

build.sh

\

#! /bin/bash # # usage: ./build.sh # it builds project and produces the armhf click package # ./build.sh -d # it builds the project and deploy it to the phone # A developer needs to change the armhf names in the following script according tuo your project # Export GOPATH= 'PWD' go get launchpad.net/go-unityscopes/v2./setup-chroot-go.sh Ubuntu-sdK-15.04 vivid Sh goscope liu-xiao-guo Ubuntu-sdK-15.04 vivid if [$# -eq 1] then if [$1 = "-d"] then echo./build-click-package.sh goscope Liu-xiao-guo Ubuntu-SDK-15.04 vivid if [$# -eq 1] then if [$1 = "-d"] then echo "Start to deploy to the phone ..." Adb push./goscope.liu-xiao-guo/goscope.liu-xiao-guo_1.0.0_armhf.click/TMP ADB shell "sudo -iu phablet pkcon --allow-untrusted install-local/TMP /goscope.liu-xiao- GUO_1.0.0_armhf. click" exit 0 fi fiCopy the code

\

From this script, we can see that when the script executes, it executes:

\

go get launchpad.net/go-unityscopes/v2
Copy the code

This statement downloads the latest “Go-UnityScope” version 2 from the address above. When you’re done downloading my template, there’s actually a directory called “SRC” inside. It already contains all the required files.

\

When we add the “-d” option, this script will automatically deploy the script to the phone for us. Remember to change the file name and directory name of the click package in the deployment section depending on your scope name.

\

setup-chroot-go.sh

\

#! /bin/bash # Function that executes a given command and compares its return command with a given one. # In case the expected and the actual return codes are different it exits # the script. # Parameters: # $1: Command to be executed (string) # $2: Expected return code (number), Can be not defined. function executeCommand() { # gets the command CMD=$1 # sets the return code expected # if it's not definedset it to 0 OK_CODE=$2 if [ -n $2 ] then OK_CODE=0 fi # executes the command ${CMD} # checks if the command was executed successfully RET_CODE=$? if [ $RET_CODE -ne $OK_CODE ] then echo "ERROR executing command: \"$CMD\"" echo "Exiting..." exit 1 fi } # ****************************************************************************** # * MAIN * # ****************************************************************************** if [ $# -ne 2 ] then echo "usage: $0 FRAMEWORK_CHROOT SERIES_CHROOT" exit 1 fi CHROOT=$1 SERIES=$2 sudo click chroot -aarmhf -f$CHROOT -s $SERIES create sudo click chroot -aarmhf -f$CHROOT -s $SERIES maint apt-get install golang-go golang-go-linux-arm golang-go-dbus-dev Golang-go-xdg -dev golang-gocheck-dev golang-gosqlite-dev golang-uuid-dev libgcrypt20-dev:armhf libglib2.0-dev:armhf libwhoopsie-dev:armhf libdbus-1-dev:armhf libnih-dbus-dev:armhf libsqlite3-dev:armhf crossbuild-essential-armhf echo "Executing go get launchpad.net/go-unityscopes/v2 ...." GOPATH=`pwd` go get launchpad.net/go-unityscopes/v2 echo "Done."Copy the code

\

This script is to help us download the Chroots we need so that we can cross-compile the ARMHF architecture to deploy on our phones. If you have installed your Own Ubuntu SDK and have the required armHF chroot installed, this script will not download anything. \

build-click-package.sh

\

#/bin/bash

# Function that executes a given command and compares its return command with a given one.
# In case the expected and the actual return codes are different it exits
# the script.
# Parameters:
#               $1: Command to be executed (string)
#               $2: Expected return code (number), may be undefined.
function executeCommand()
{
    # gets the command
    CMD=$1
    # sets the return code expected
    # if it's not definedset it to 0
    OK_CODE=$2
    if [ -n $2 ]
    then
        OK_CODE=0
    fi
    # executes the command
    eval ${CMD}

    # checks if the command was executed successfully
    RET_CODE=$?
    if [ $RET_CODE -ne $OK_CODE ]
    then
	echo ""
        echo "ERROR executing command: \"$CMD\""
        echo "Exiting..."
        exit 1
    fi
}

# ******************************************************************************
# *                                   MAIN                                     *
# ******************************************************************************

if [ $# -ne 4 ]
then
    echo "usage: $0 SCOPE_NAME DEVELOPER_NAME FRAMEWORK_CHROOT SERIES_CHROOT"
    exit 1
fi

SCOPE_NAME=$1
DEVELOPER_NAME=$2
CHROOT=$3
SERIES=$4

CURRENT_DIR=`pwd`

FILE_NAME="${SCOPE_NAME}.${DEVELOPER_NAME}"
MANIFEST_NAME="${SCOPE_NAME}.${DEVELOPER_NAME}"

echo -n "Removing ${FILE_NAME} directory... "
executeCommand "rm -rf ./${FILE_NAME}"
echo "Done"

echo -n "Creating clean ${FILE_NAME} directory... "
executeCommand "mkdir -p ${FILE_NAME}/${FILE_NAME}"
echo "Done"

echo -n "Copying scope ini file... "
executeCommand "cp $SCOPE_NAME.ini ${FILE_NAME}/${FILE_NAME}/${FILE_NAME}_${SCOPE_NAME}.ini"
echo "Done"

echo -n "Copying the logo file ... "
executeCommand "cp logo.jpg ${FILE_NAME}/${FILE_NAME}/logo.jpg"
echo "Done"

echo -n "Copying the icon file ... "
executeCommand "cp icon.jpg ${FILE_NAME}/${FILE_NAME}/icon.jpg"
echo "Done"

echo -n "Setting scope name in ini file..."
executeCommand 'sed -i "s/%SCOPE_NAME%/${FILE_NAME}/g" ${FILE_NAME}/${FILE_NAME}/${FILE_NAME}_${SCOPE_NAME}.ini'
echo "Done"

echo -n "Copying scope json files... "
executeCommand "cp *.json ${FILE_NAME}/"
echo "Done"

echo -n "Setting scope name in manifest file..."
executeCommand 'sed -i "s/%SCOPE_NAME%/${MANIFEST_NAME}/g" ${FILE_NAME}/manifest.json'
echo "Done"

echo -n "Cross compiling ${FILE_NAME}..."
executeCommand "click chroot -aarmhf -f$CHROOT -s $SERIES run CGO_ENABLED=1 GOARCH=arm GOARM=7 PKG_CONFIG_LIBDIR=/usr/lib/arm-linux-gnueabihf/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig GOPATH=/usr/share/gocode/:$GOPATH CC=arm-linux-gnueabihf-gcc CXX=arm-linux-gnueabihf-g++ go build -ldflags '-extld=arm-linux-gnueabihf-g++' -o ${FILE_NAME}/${FILE_NAME}/${FILE_NAME}"
echo "Done"

executeCommand "cd ./${FILE_NAME}"

echo -n "Building click package ... "
executeCommand "click build ./"
echo "Done"

executeCommand "cd .."
Copy the code

\

We can cross-compile our GoScope armHF Click package from this script. When used, as shown in build.sh above:

\

$./build-click-package.sh goscope liu-xiao-guo Ubuntu - SDK-15.04 vividCopy the code

Here, we pass in the project’s Scope name, developer’s name, Framework, and Ubuntu series number.

\

\

run.sh

\

#! /bin/bash # # This is the script to build and run the scope on desktop environment. # A developer needs to change the Following variable according to your projectt # SCOPE_NAME=goscope # DEVELOPER_NAME=liu-xiao-guo # # function executeCommand() { # gets the command CMD=$1 # sets the return code expected # if it's not definedset it to 0 OK_CODE=$2  if [ -n $2 ] then OK_CODE=0 fi # executes the command eval ${CMD} # checks if the command was executed successfully RET_CODE=$? if [ $RET_CODE -ne $OK_CODE ] then echo "" echo "ERROR executing command: \"$CMD\"" echo "Exiting..." exit 1 fi } export GOPATH=`pwd` SCOPE_NAME=goscope DEVELOPER_NAME=liu-xiao-guo FILE_NAME="${SCOPE_NAME}.${DEVELOPER_NAME}" echo -n "Removing ${FILE_NAME} directory... " executeCommand "rm -rf ./${FILE_NAME}" echo "Done" echo -n "Copying scope ini file... " executeCommand "cp $SCOPE_NAME.ini ${FILE_NAME}_${SCOPE_NAME}.ini" echo "Done" echo -n "Setting scope name in ini file..." executeCommand 'sed -i "s/%SCOPE_NAME%/${FILE_NAME}/g" ${FILE_NAME}_${SCOPE_NAME}.ini' echo "Done" echo -n "Building the  scope" executeCommand "go build -o ${FILE_NAME}" unity-scope-tool ${FILE_NAME}_${SCOPE_NAME}.iniCopy the code

This script is used to compile our Scope in the Desktop environment and launch our Scope using unity-scope-tool:

\

\

\

\

\

clean.sh

\

#! /bin/bash # # This file cleans all of the intermediate files produced during the compilation. For each project # a developer needs to customize the variables # SCOPE_NAME # DEVELOPER_NAME # # function executeCommand() { # gets the command CMD=$1 # sets the return code expected # if it's not definedset it to 0 OK_CODE=$2 if [ -n $2 ] then OK_CODE=0 fi # executes the command eval ${CMD} # checks if the command was executed successfully RET_CODE=$? if [ $RET_CODE -ne $OK_CODE ] then echo "" echo "ERROR executing command: \"$CMD\"" echo "Exiting..." exit 1 fi } SCOPE_NAME=goscope DEVELOPER_NAME=liu-xiao-guo FILE_NAME="${SCOPE_NAME}.${DEVELOPER_NAME}" echo -n "Removing  ${FILE_NAME} directory... " executeCommand "rm -rf ./${FILE_NAME}" echo "Done" echo -n "Removing ${FILE_NAME}_${SCOPE_NAME}.ini ..." executeCommand "rm -f ${FILE_NAME}_${SCOPE_NAME}.ini" echo "Done" echo -n "Removing ${FILE_NAME} ..." executeCommand "rm -f ${FILE_NAME}" echo "Done" echo -n "Removing pkg directory ..." executeCommand "rm -rf pkg" echo "Done"Copy the code

\

This script is designed so that we can remove any intermediate files that we create during compilation.

\

goscope.go

\

package main

import (
	"launchpad.net/go-unityscopes/v2"
	"log"
	"encoding/json"
	"net/url"
	"net/http"
)


const searchCategoryYellow = `{
    "schema-version" : 1,
    "template" : {
        "category-layout" : "vertical-journal",
        "card-layout": "horizontal",
        "card-size": "small",
        "collapsed-rows": 0
     },
    "components" : {
        "title" : "title",
        "subtitle":"subtitle",
        "summary":"summary",
        "art":{
        	"field": "art",
       		"aspect-ratio": 1
        }
    }
}`

const searchCategoryTemplate = `{
    "schema-version" : 1,  
    "template" : {  
        "category-layout" : "carousel",  
        "card-size": "large",  
        "overlay" : true  
    },  
    "components" : {  
        "title" : "title",  
        "art" : {  
            "field": "art",  
            "aspect-ratio": 1.6,  
            "fill-mode": "fit"  
        }  
    }  
}`

// SCOPE ***********************************************************************

var scope_interface scopes.Scope

type MyScope struct {
	BaseURI string
	Key     string
	URI		string
	Dir     string	
	base *scopes.ScopeBase
}

type WathereResponse struct {
	WeatherList []Weather `json:"results"`
	Date string `json:"date"`
}

type Weather struct {
	CurrentCity string `json:"currentCity"`
	Pm25 string `json:"pm25"`
	IndexList []Index `json:"index"`
	Weather_datalist []Weather_data `json:"weather_data"`
}

type Index struct {
	Title string `json:"title"`
	Zs string `json:"zs"`
	Tipt string `json:"tipt"`
	Des string `json:"des"`
}

type Weather_data struct {
	Date string `json:"date"`
	DayPictureUrl string `json:"dayPictureUrl"`
	NightPictureUrl string `json:"nightPictureUrl"`
	Weather string `json:"weather"`
	Wind string `json:"wind"`
	Temperature string `json:"temperature"`
}

func (s *MyScope) buildUrl(url2 string, params map[string]string) string {
	query := make(url.Values)
	for key, value := range params {
		query.Set(key, value)
	}
	log.Println(url2 + query.Encode())
	return url2 + query.Encode()
}

// This is used to get results from a webservice
func (s *MyScope) get(url string, params map[string]string, result interface{}) error {
	resp, err := http.Get(s.buildUrl(url, params))
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	decoder := json.NewDecoder(resp.Body)
	return decoder.Decode(result)
}

func (s *MyScope) Search(q *scopes.CannedQuery, metadata *scopes.SearchMetadata, reply *scopes.SearchReply, cancelled <-chan bool) error {
	root_department := s.CreateDepartments(q, metadata, reply)
	reply.RegisterDepartments(root_department)

	query := q.QueryString()
	log.Println(query)	
	
	// Try to get the city name
	loc := metadata.Location()
	city := loc.City;
	log.Println("city: ", city)
	
	if query == "" {
		if q.DepartmentID() == "" {
			query = city
		} else {
			query = q.DepartmentID()
		}			
	} 
	
	log.Println("query: ", query)
	
	var response WathereResponse
	
	if err := s.get(s.BaseURI, map[string]string{"location": query, "ak": s.Key, "output": "json"}, &response); err != nil {
		return err
	} else {
		log.Println("there is no error!")
	}
	
	// log.Println(response)
	date := response.Date;
	log.Println("date: ", date)
	
	var cat *scopes.Category;
	
	if len(q.QueryString()) == 0 && q.DepartmentID() == "" {
		cat = reply.RegisterCategory("weather", query, "", searchCategoryTemplate)
	} else {
		cat = reply.RegisterCategory("weather", "", "", searchCategoryTemplate)
	}
		
	
	for _, data := range response.WeatherList {
		result := scopes.NewCategorisedResult(cat)
		result.SetURI(s.URI)

//		log.Println("Current city:", data.CurrentCity)
//		log.Println("PM25: ", data.Pm25)
		
		var yellocalendar string = ""
		for _, index := range data.IndexList {
//			log.Println("title: ", index.Title)
//			log.Println("zs: ", index.Zs)
//			log.Println("tipt: ", index.Tipt)
//			log.Println("Des: ", index.Des)
			
			yellocalendar += index.Title + " "
			yellocalendar += index.Zs + " "
			yellocalendar += index.Tipt + " "
			yellocalendar += index.Des
		}
		
		for i, weather := range data.Weather_datalist {
//			log.Println("date: ", weather.Date)
//			log.Println("dayPictureUrl: ", weather.DayPictureUrl)
//			log.Println("nightPictureUrl: ", weather.NightPictureUrl)
//			log.Println("weather: ",weather.Weather)
//			log.Println("wind: ", weather.Wind)
//			log.Println("temperature: ", weather.Temperature)
			
			result.SetTitle(weather.Date)
			result.SetArt(weather.DayPictureUrl)
			result.Set("wind", weather.Wind)
			result.Set("weather", weather.Weather)
			result.Set("temperature", weather.Temperature)
			
			if err := reply.Push(result); err != nil {
				return err
			}
			
			result.SetArt(weather.NightPictureUrl)
			if err := reply.Push(result); err != nil {
				return err
			}			
			
			// Push the yellow calender now
			if i == 0  {
				cat1 := reply.RegisterCategory("weather1", "今天天气", "", searchCategoryYellow)
				result1 := scopes.NewCategorisedResult(cat1)								
				
				result1.SetURI(s.URI)
				result1.SetTitle(date)
				result1.SetArt(weather.DayPictureUrl)
				result1.Set("subtitle", weather.Weather + " " + weather.Wind + " " +  weather.Temperature + "  PMI: " +  data.Pm25)
				result1.Set("summary", yellocalendar)
				
				if err := reply.Push(result1); err != nil {
					return err
				}					
			}		
		}		
	}
	
	return nil
}

func (s *MyScope) Preview(result *scopes.Result, metadata *scopes.ActionMetadata, reply *scopes.PreviewReply, cancelled <-chan bool) error {
	layout1col := scopes.NewColumnLayout(1)
	layout2col := scopes.NewColumnLayout(2)
	layout3col := scopes.NewColumnLayout(3)

	// Single cyolumn layout
	layout1col.AddColumn("header", "image",  "wind", "weather", "temperature", "summary", "actions")

	// Two column layout
	layout2col.AddColumn("header")
	layout2col.AddColumn("image", "wind", "weather", "temperature", "summary", "actions")

	// Three cokumn layout
	layout3col.AddColumn("header")
	layout3col.AddColumn("image", "wind", "weather", "temperature","summary", "actions")
	layout3col.AddColumn()

	// Register the layouts we just created
	reply.RegisterLayout(layout1col, layout2col, layout3col)

	header := scopes.NewPreviewWidget("header", "header")

	// It has title and a subtitle properties
	header.AddAttributeMapping("title", "title")
	header.AddAttributeMapping("subtitle", "subtitle")

	// Define the image section
	image := scopes.NewPreviewWidget("image", "image")
	// It has a single source property, mapped to the result's art property
	image.AddAttributeMapping("source", "art")

	// Define the summary section
	description := scopes.NewPreviewWidget("summary", "text")
	description.AddAttributeMapping("text", "summary")

	wind := scopes.NewPreviewWidget("wind", "text")
	wind.AddAttributeMapping("text", "wind")

	weather := scopes.NewPreviewWidget("weather", "text")
	weather.AddAttributeMapping("text", "weather")

	temperature := scopes.NewPreviewWidget("temperature", "text")
	temperature.AddAttributeMapping("text", "temperature")

	// build variant map.
	var uri string

	if err := result.Get("uri", &uri); err != nil {
		log.Println(err)
	}

	tuple1 := make(map[string]interface{})
	tuple1["id"] = "open"
	tuple1["label"] = "Open"
	tuple1["uri"] = uri

	actions := scopes.NewPreviewWidget("actions", "actions")
	actions.AddAttributeValue("actions", []interface{}{tuple1})

	var summary string
	if err := result.Get("summary", &summary); err != nil {
		log.Println(err)
	}

	if len(summary) > 0 {
		reply.PushWidgets(header, image, description, actions)
	} else {
		reply.PushWidgets(header, image, wind, weather, temperature, actions)
	}

	return nil
}

func (s *MyScope) SetScopeBase(base *scopes.ScopeBase) {
	s.base = base
}


func (s *MyScope) GetSubdepartments1(query *scopes.CannedQuery,
	metadata *scopes.SearchMetadata,
	reply *scopes.SearchReply) *scopes.Department {
	active_dep, err := scopes.NewDepartment("wuhan", query, "湖北")
	
	if err == nil {
//		active_dep.SetAlternateLabel("Rock Music Alt")
		department, _ := scopes.NewDepartment("武汉", query, "武汉")
		active_dep.AddSubdepartment(department)

		department2, _ := scopes.NewDepartment("宜昌", query, "宜昌")
		active_dep.AddSubdepartment(department2)
				
		department3, _ := scopes.NewDepartment("随州", query, "随州")
		active_dep.AddSubdepartment(department3)
	}

	return active_dep
}

func (s *MyScope) GetSubdepartments2(query *scopes.CannedQuery,
	metadata *scopes.SearchMetadata,
	reply *scopes.SearchReply) *scopes.Department {
	active_dep, err := scopes.NewDepartment("changsha", query, "湖南")
	
	if err == nil {
		department, _ := scopes.NewDepartment("长沙", query, "长沙")
		active_dep.AddSubdepartment(department)

		department2, _ := scopes.NewDepartment("株洲", query, "株洲")
		active_dep.AddSubdepartment(department2)
	}

	return active_dep
}

func (s *MyScope) CreateDepartments(query *scopes.CannedQuery,
	metadata *scopes.SearchMetadata,
	reply *scopes.SearchReply) *scopes.Department {
		
	department, _ := scopes.NewDepartment("", query, "选择地点")

	dept1 := s.GetSubdepartments1(query, metadata, reply)
	if dept1 != nil {
		department.AddSubdepartment(dept1)
	}

	dept2 := s.GetSubdepartments2(query, metadata, reply)
	if dept2 != nil {
		department.AddSubdepartment(dept2)
	}

	return department
}

// MAIN ************************************************************************

func main() {
	scope := &MyScope {
		BaseURI: "http://api.map.baidu.com/telematics/v3/weather?",
		Key:     "DdzwVcsGMoYpeg5xQlAFrXQt",
		URI: 	 "http://www.weather.com.cn/html/weather/101010100.shtml",
		Dir:     "",
	}
	
	scope_interface = scope
	
	if err := scopes.Run(scope); err != nil {
		log.Fatalln(err)
	}
}
Copy the code

This is our Go language programming for GoScope. In this GoScope, we use Baidu’s weather API to display weather data. The whole scope design is actually similar to the C++ scope design, but it is more concise and clear.

\

We can package our Scope and deploy it on our mobile phone by using the following command:

\

$./build.sh -d
Copy the code

\

If we just want to get the ARMHF click package, we don’t need the “-d” argument. Running conditions on mobile phones:

\

\

\

    

\

\

How to run Scope

\

We can do this in Terminal:

[plain]  view plain copy

  1. $chmod +x *.sh  

Run the above command to make the. Sh file executable

[plain]  view plain copy

  1. $./run.sh  

Run our Scope on your Desktop through the script above

[plain]  view plain copy

  1. $./build.sh -d  

\

With our script execution above, GoScope can be compiled and deployed to the phone

[plain]  view plain copy

  1. $./clean.sh  

Clear all compiled intermediate files \ by executing the script above