In my earlier post, we saw different ways in which we can use Gomobile. In this post I’ll try illustrating how to incorporate Gomobile into a mobile application using the bind
command.
Prerequisites
-
Ensure that you’ve setup Go and Gomobile in your machine
-
Install NDK (If you are generating a Android library)
Three Step Recipe
Step 1 - Write a Go Package
-
Create a go package in
$GOPATH/src/github.com/$username/gomobile_contact
-
Create the following files
In the above linked files I’ve made a network request, parsed the response and unmarshalled it into a Contact object and returned the first Contact’s name. This is an example of a simple business logic component that can be written in Go and ported as a library.
Step 2 - Generate libraries
Use the following commands to generate libraries for iOS / Android applications
gomobile bind --target=ios #ios
gomobile bind --target=android #android
Step 3 - Import library into Application
Gomobile generates a .aar/jar for Android and .Framework for iOS
Import the packages into your application and call the FetchContactName()
method which returns the first contact’s name.
VoilĂ ! You’ve succesfully generated a library using Go and integrated into your application :)