Get Started with Go using Martini

    Start by signing up for a free trial account that you can use to experiment with and learn about our services. The free trial account comes with free credits, and you can add more as you go along. You can also add a phone number to your account to start testing the full range of our voice and SMS features. A page in our support portal walks you through the signup process.

    You can start making and receiving calls either by using our PHLO visual workflow builder or our APIs and XML documents. Follow the instructions in one of the tabs below.

    Make Your First Outbound Call

    To make your first outbound call, you can create and deploy a PHLO in just a few clicks using the PHLO canvas. PHLO also lets you visually construct your entire use-case. With PHLO, only pay for calls you make/receive. Building with PHLO is free.

    Prerequisites

    1. Create a Plivo account (if you don’t have one already): Sign up with your work email address and complete the phone verification step using your mobile number.
    2. Set Up Your Go Dev environment: To set up your dev environment in Go programming language, please refer to the instructions available in the Set Up Your GO Dev Environment section.
    3. Buy a Plivo Number(optional): You must have a voice-enabled Plivo phone number if you wish to receive incoming calls. Purchase numbers from the Numbers section of your Plivo Console. It is also possible to purchase numbers using the Numbers API.

    Create the PHLO

    Create a PHLO to make your first outbound call by following these instructions:

    Create a PHLO for outbound calls

    • On the side navigation bar, click PHLO. The PHLO page will appear and display your existing PHLOs, if any exist. If this is your first PHLO, then the PHLO page will be empty.
    • Click Create New PHLO to build a new PHLO.
    • In the Choose your use-case window, click Build my own. The PHLO canvas will appear with the Start node.
      Note: The Start node is the starting point of any PHLO. You can choose between the four available trigger states of the start node; Incoming SMS, Incoming Call, and API Request. For this PHLO, we will use the API Request trigger state.
    • From the list of components on the left-hand side, drag and drop the Initiate Call component onto the canvas. This will add an Initial Call node onto the canvas.
    • Connect the Start node with the Initiate Call node, using the API Request trigger state.
    • Configure the Initiate Call node with the caller ID using the From field. Enter the destination number you wish to call in the To field.
    • Once you have configured the node, click Validate to save the configurations.
    • Similarly, create a node for the Play Audio component and connect it to the Initiate Call node using the Answered trigger state.
    • Next, configure the Play Audio node to play a specific message to the user. For example, “Hello! You just received your first inbound call”.
    • Connect the Initiate Call node with the Play Audio node, using the Answered trigger state.
    • After you complete the configurations, provide a recognizable name for your PHLO and click Save. Your PHLO is now ready. You can trigger the PHLO and test it out. For more information, refer to the following section.

    Set Up Your Go Martini Dev Environment

    You must set up and install Go and Plivo’s Go SDK to make your first call. Here’s how.

    Install Go

    You can install Go from the Official Installer.

    Install Plivo and Martini Go Packages

    • Create a project directory, run the following command:

      $ mkdir mygoapp
      
    • Change the directory to our project directory in the command line:

      $ cd mygoapp
      
    • You can install the Plivo and Martini Go packages using the go command.

      $ go get github.com/plivo/plivo-go
      $ go get github.com/go-martini/martini
      
    • You can also install by cloning the Plivo Go repository and Martini repository into your GOPATH.

    Trigger the PHLO

    Once you have created and configured your PHLO, copy the PHLO_ID from here. Integrate a PHLO into your application workflow by making an API request to trigger the PHLO with the required payload.

    With Static Payload

    Once you have created and setup your Go dev envrironment, you can go to your Plivo Consolse and copy the PHLO_ID. Integrate a PHLO into your application workflow by making an API request to trigger the PHLO with the required payload.

    Note: When you configure the params while creating the PHLO, the values are hardcoded and act as static payload.

    With Static Payload

    Code

    Now, create a file called TriggerPhlo.go and paste the following code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    
    package main
    
    import (
    	"fmt"
    	"plivo-go"
    )
    // Initialize the following params with corresponding values to trigger resources
    const authId = "auth_id"
    const authToken = "auth_token"
    const phloId = "phlo_id"
    
    func main() {
    	testPhloRunWithoutParams()
    }
    
    func testPhloRunWithoutParams() {
    	phloClient, err := plivo.NewPhloClient(authId, authToken, &plivo.ClientOptions{})
    	if err != nil {
    		panic(err)
    	}
    	phloGet, err := phloClient.Phlos.Get(phloId)
    	if err != nil {
    		panic(err)
    	}
    	response, err := phloGet.Run(nil)
    	if err != nil {
    		panic(err)
    	}
    	fmt.Printf("Response: %#v\n", response)
    }
    

    With Dynamic Payload

    To use dynamic values for the parameters, use the liquid templating params while creating the PHLO and pass the values while triggering the PHLO.

    With Dynamic Payload

    Code

    Now, create a file called TriggerPhlo.go and paste the following code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    
    package main
    
    import (
    	"fmt"
    	"plivo-go"
    )
    // Initialize the following params with corresponding values to trigger resources
    const authId = "auth_id"
    const authToken = "auth_token"
    const phloId = "phlo_id"
    
    func main() {
    	testPhloRunWithParams()
    }
    
    func testPhloRunWithParams() {
    	phloClient, err := plivo.NewPhloClient(authId, authToken, &plivo.ClientOptions{})
    	if err != nil {
    		panic(err)
    	}
    	phloGet, err := phloClient.Phlos.Get(phloId)
    	if err != nil {
    		panic(err)
    	}
    	//pass corresponding from and to values
    	type params map[string]interface{}
    	response, err := phloGet.Run(params{
    		"from": "+14157778888",
    		"to":   "+14157778889",
    	})
    
    	if err != nil {
    		println(err)
    	}
    	fmt.Printf("Response: %#v\n", response)
    }
    

    Get your Auth_ID and Auth_token from your dashboard AUTHID

    You can find the PHLO_ID on the PHLO Listing page. PHLO Listing

    Test and Validate

    Save the file and use the below command to run it.

    $ go run TriggerPhlo.go
    
    Note: If you are using a Plivo Trial account for this example, you can only make calls to phone numbers that have been verified with Plivo. Phone numbers can be verified at the Sandbox Numbers page.

    Receive Your First Inbound call

    Create and deploy a PHLO to receive your first inbound call with a few clicks on the PHLO canvas. PHLO also lets you visually construct your entire use-case. With PHLO, only pay for calls you make/receive. Building with PHLO is free.

    Prerequisites

    1. Create a Plivo account (if you don’t have one already): Sign up with your work email address and complete the phone verification step using your mobile number.
    2. Buy a Plivo number: You must have a voice-enabled Plivo phone number to receive incoming calls. Purchase numbers from the Numbers section of your Plivo Console. It is also possible to purchase numbers using the Numbers API.
    3. PHLO Application: When you receive a call on a Plivo voice-enabled number, you can control the call flow by associating a PHLO application to that Plivo phone number. Plivo will fetch the PHLO associated with the number and expect valid instructions via PHLO to handle the call.

    Create the PHLO

    You can create a PHLO by referring to the below instructions to receive your first incoming call:

    Create a PHLO to receive incoming call

    • On the side navigation bar, click PHLO. The PHLO page will appear and display your existing PHLOs, if any exist. If this is your first PHLO, then the PHLO page will be empty.
    • Click Create New PHLO to build a new PHLO.
    • In the Choose your use-case window, click Build my own. The PHLO canvas will appear with the Start node.
      Note: The Start node is the starting point of any PHLO. You can choose between the four available trigger states of the start node; Incoming SMS, Incoming Call, and API Request. For this PHLO, we will use the API Request trigger state.
    • From the list of components on the left-hand side, drag and drop the Play Audio component onto the canvas. This will add a Play Audio node onto the canvas.
    • Connect the Start node with the Play Audio node, using the Incoming Call trigger state.
    • Configure the Play Audio node to play a specific message to the user. For example, “Hello! You just received your first inbound call”.
    • Once you have configured the node, click Validate to save the configurations.
    • After you complete the configurations, provide a recognizable name for your PHLO and click Save. Your PHLO is now ready.

    Assign the PHLO to a Plivo Number for Incoming Calls

    Once you have created and configured your PHLO, assign your PHLO to a Plivo number.

    To assign a PHLO to a number:

    1. Log in to your Plivo Console
    2. On the Product Navigation bar, click Phone Numbers.
    3. On the Numbers page, under Your Numbers, click the phone number you wish to use for the PHLO.
    4. In the Number Configuration window, select PHLO from the Application Type list.
    5. From the PHLO Name list, select the PHLO you wish to use with the phone number, and then click Update Number.

    Assign PHLO to a Plivo Number

    If you have not purchased a phone number yet, you can buy a phone number(s) by referring to the instructions available here.

    Test and Validate

    You can now make a call to your Plivo phone number to receive an incoming call and see how the inbound call is handled using PHLO.

    For more information about creating a PHLO app, see the PHLO User Guide.
    For information on components and their variables, see the PHLO Components Library.

    Forward an Incoming call

    To forward an incoming call, you can create and deploy a PHLO with a few clicks on the PHLO canvas.

    Prerequisites

    1. Create a Plivo account (if you don’t have one already): Sign up with your work email address and complete the phone verification step using your mobile number.
    2. Buy a Plivo number: You must have a voice-enabled Plivo phone number to receive incoming calls. Purchase numbers from the Numbers section of your Plivo Console. It is also possible to purchase numbers using the Numbers API.
    3. PHLO Application: When you receive a call on a Plivo voice-enabled number, you can control the call flow by associating a PHLO application to that Plivo phone number. Plivo will fetch the PHLO associated with the number and expect valid instructions via PHLO to handle the call.

    Create the PHLO

    You can create a PHLO by referring to the below instructions to forward an incoming call:

    Create a PHLO to receive incoming call

    • On the side navigation bar, click PHLO. The PHLO page will appear and display your existing PHLOs, if any exist. If this is your first PHLO, then the PHLO page will be empty.
    • Click Create New PHLO to build a new PHLO.
    • In the Choose your use-case window, click Build my own. The PHLO canvas will appear with the Start node.
      Note: The Start node is the starting point of any PHLO. You can choose between the four available trigger states of the start node; Incoming SMS, Incoming Call, and API Request. For this PHLO, we will use the API Request trigger state.
    • From the list of components on the left-hand side, drag and drop the Call Forward component onto the canvas. This will add a Call Forward node onto the canvas.
    • Connect the Start node with the Call Forward node, using the Incoming Call trigger state.
    • Configure the Call Forward node with the phone number to which you want to forward the call. For example, in this case, “+14157778889”.
    • Once you have configured the node, click Validate to save the configurations.
    • After you complete the configurations, provide a recognizable name for your PHLO and click Save. Your PHLO is now ready.

    Assign the PHLO to a Plivo Number to Forward Incoming Calls

    Once you have created and configured your PHLO, assign your PHLO to a Plivo number.

    To assign a PHLO to a number:

    1. Log in to your Plivo Console
    2. On the Product Navigation bar, click Phone Numbers.
    3. On the Numbers page, under Your Numbers, click the phone number you wish to use for the PHLO.
    4. In the Number Configuration window, select PHLO from the Application Type list.
    5. From the PHLO Name list, select the PHLO you wish to use with the phone number, and then click Update Number.

    Assign PHLO to a Plivo Number

    If you have not purchased a phone number yet, you can buy a phone number(s) by referring to the instructions available here.

    Test and Validate

    You can now make a call to your Plivo phone number and see how the inbound call is forwarded to the phone number specified in the PHLO.

    For more information about creating a PHLO app, see the PHLO User Guide.
    For information on components and their variables, see the PHLO Components Library.

    Install Go and the Plivo Go Server SDK

    You must set up and install Go and Plivo’s Go SDK to make your first call. Here’s how.

    Install Go

    You can install Go from the Official Installer.

    Install Plivo Go and Martini packages

    • Create a project directory, run the following command:

      $ mkdir mygoapp
      
    • Change the directory to our project directory in the command line:

      $ cd mygoapp
      
    • You can install the Plivo and Martini Go packages using the go command.

      $ go get github.com/plivo/plivo-go
      $ go get github.com/go-martini/martini
      
    • You can also install by cloning the Plivo Go repository and Martini repository into your GOPATH.

    Make your first Outbound Call

    Prerequisites

    This section will guide you through how to use Plivo APIs to make voice calls from your application. First, let’s make sure you meet these prerequisites before we dive into the code.

    • Plivo Auth Id and Auth Token: You will find your Plivo Auth Id and Auth Token on the home screen of your Plivo Console. Click here to sign-up for a Plivo account if you haven’t already!

      Find Your Auth Credentials on Plivo Console

    • Plivo Phone Number(Optional): Purchase numbers from the Numbers section of your Plivo Console and use the same as the caller ID for the outbound call. This number will also help you receive incoming calls as you must have a voice-enabled Plivo phone number to do the same. Please note that you can also purchase numbers using the Numbers API.

      Buy a New Plivo Number

    • Answer Url: When a call is answered by the destination_number, you can control the call flow with the help of the answer_url set in the API request. Plivo will invoke the answer_url specified as soon as the call is answered and expect a valid XML response with instructions to handle the call. For example, you can use https://s3.amazonaws.com/static.plivo.com/answer.xml as answer_url to test your first outgoing call. The XML response of this is:

      <Response>
      <Speak>Congratulations! You've made your first outbound call!</Speak>
      </Response>
      

      As you can tell, the XML above holds instructions to say ‘Congratulations! You’ve made your first outbound call!’ to the callee. You can find the entire list of Plivo XML verbs and their details in the XML Reference section of the website here.

    Now, create a file called MakeCall.go and paste the following code:

    Code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    
    package main
    
    import "fmt"
    import "github.com/plivo/plivo-go"
    
    func main() {
    	client, err := plivo.NewClient("<auth_id>","<auth_token>", &plivo.ClientOptions{})
    	if err != nil {
    		panic(err)
    	}
    	response, err := client.Calls.Create(
    		plivo.CallCreateParams{
    			From: "Caller_ID",
    			To: "Destination_Number",
    			AnswerURL: "http://s3.amazonaws.com/static.plivo.com/answer.xml",
    			AnswerMethod: "GET",
    		},
    	)
    	if err != nil {
    		panic(err)
    	}
    	fmt.Printf("Response: %#v\n", response)
    }
    
    Note:
    • Replace the placeholders auth_id & auth_token with your credentials from Plivo Console
    • We recommend that you store your credentials in the auth_id & auth_token environment variables, so as to avoid the possibility of accidentally committing them to source control. If you do this, you can initialize the client with no arguments and it will automatically fetch them from the environment variables
    • You can use os.Setenv & os.Getenv function to store environment variables and fetch them while initializing the client.
    • Replace the placeholder Caller_ID with the Phone number which you have purchased and Destination_Number with the phone number you will be making call to
    • Both Caller_ID and Destination_Number should be in E.164 format
    • Destination_Number can also be a SIP endpoint. In case you are calling a SIP endpoint, the Destination_Number placeholder should be a valid SIP URI. Example: sip:john1234@phone.plivo.com

    save the file and use the below command to run it.

    go run MakeCall.go
    
    Note: If you are using a Plivo Trial account for this example, you can only make calls to phone numbers that have been verified with Plivo. Phone numbers can be verified at the Sandbox Numbers page.

    Receive Your First Inbound Call

    Prerequisites

    In addition to having at least one voice-enabled Plivo phone number that is needed to receive incoming calls (as was mentioned earlier), you need the following:

    Answer URL & Callback URLs

    When a call is received on a Plivo voice-enabled number, you can control the call flow by declaring an answer URL for your Plivo application associated with that Plivo phone number. Plivo will invoke the answer URL specified and expect a valid XML response to handle the call.

    Notice how the concept of Answer URLs applies to both outbound API calls as well as incoming calls to your Plivo numbers. In the outbound API call example above, we specified the answer URL along with the make call API request, whereas in the case of incoming calls to Plivo numbers, the answer URL is specified in the Plivo application associated with the phone number.

    In addition to requests to the answer URL, Plivo initiates HTTP requests to your application server through the course of a call based on the specific XML elements in your answer XML. Such requests can be broadly classified into two categories:

    Action URL requests: XML instructions to carry forward the call are expected in response to these requests. These requests are typically invoked at the end of an XML element’s execution. For example: when an IVR input is received from the caller during a GetInput XML execution.

    Callback URL requests: No XML instructions are expected in response to these requests. Such requests serve as webhooks to notify your application server of important events through the course of an XML element’s execution. For example: when a conference participant is muted or unmuted.

    Web Server

    To be able to host Answer and Callback URLs and to be able to provide valid XMLs and accept notifications on these URLs respectively, you need to host a webserver at your end.

    Set up Go Martini Server for Incoming Calls & Callbacks

    In this section, we’ll walk you through how to set up a Go server in under five minutes and start handling incoming calls & callbacks.

    Use the following code snippet to start a local server.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    package main
    
    import (
    	"github.com/go-martini/martini"
    	"github.com/plivo/plivo-go/xml"
    	"net/http"
    )
    
    func main() {
    	m := martini.Classic()
    	m.Get("/receive_call/", func(w http.ResponseWriter, r *http.Request) string {
    		w.Header().Set("Content-Type", "application/xml")
    
    		return xml.ResponseElement{Contents: []interface{}{
    			new(xml.SpeakElement).
    				AddSpeak("Hello, you just received your first call"),
    		}}.String()
    	})
    	m.Run()
    }
    

    Save this code in any file (name the file something like receive_call.go). To run this file on the server, go to the folder where this file resides and use the following command:

      go run receive_call.go
    

    And you should see your basic server app in action on http://localhost:8080/receive_call/

    Exposing your local server to the internet

    To receive Incoming Calls and to handle callbacks, your local server should be able to connect with Plivo API service, Ngrok is a tunneling software used to expose a web server running on your local machine to the internet. Using Ngrok you can set webhooks which can talk to Plivo server.

    ngrok block diagram

    You can download and install ngrok from here. Follow the detailed configuration instructions to get started.

    Run ngrok on the port which currently hosts your application. For example, if your port number is 80, run the following command:

    ./ngrok http <port_on_which_your_local_server_is_running>
    

    This will give you a UI with links that look like ngrok.io/* which you can use to access your local server using the public network.

    Sample ngrok CLI

    Create a Plivo Application

    1. Create an Application by visiting the Application Page and click on New Application. You can also use Plivo’s Application API.
    2. Give your application a name. Let’s call it Receive_call. Enter your server URL (e.g. http://example.com/receive_call/) in the Answer URL field and set the method as POST. See our Application API docs to learn how to modify your application through our APIs.
    3. Click on Create Application to save your application.

    Create Application

    Assign a Plivo number to your app

    1. Navigate to the Numbers page and select the phone number you want to use for this app.
    2. Select Receive Call (name of the app) from the Plivo App dropdown list.
    3. Click on Update to save.

    Assign Phone Number to Receive Call App

    Test and validate

    Make a call to your Plivo number using a regular mobile phone. Plivo will send a request to your Answer URL requesting for a valid XML response and process the call. Meanwhile, the parameters listed in the XML Request - call status documentation will also be sent to your server.

    Forward an Incoming call

    To forward an incoming call, you need to use Dial XML.

    • You should set up the dial XML document in your server
    • URL of the dial XML in your server has to be set up as the answer_url of the app assigned to the Plivo number.
    • During an incoming call to your Plivo number, Plivo will send a request to the answer_url expecting a valid XML to process the incoming call.
    • As the response would be a dial XML, the call will be forwarded to the number defined in the XML response.
    Note: Phone number must be a Plivo phone number that is Voice-enabled. You can purchase a Plivo number from the Buy Numbers tab on your Plivo Console and filter the Phone Numbers by selecting Voice in the features option to buy Voice enabled numbers.

    Create a file called forward_call.go and paste the following code.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    
    package main
    
    import (
    	"net/http"
    	"plivo-go/xml"
    )
    
    func handler(w http.ResponseWriter, r *http.Request) {
    	response := xml.ResponseElement{
    		Contents: []interface{}{
    			new(xml.DialElement).
    				SetContents(
    					[]interface{}{
    						new(xml.NumberElement).
    							SetContents("15671234567"),
    					},
    				),
    		},
    	}
    	w.Write([]byte(response.String()))
    }
    
    func main() {
    	http.HandleFunc("/forward_call/", handler)
    	http.ListenAndServe(":8080", nil)
    }
    
    Note: Create an application in the Plivo console with your Server URL in the answer_url field and assign the app to a Plivo number.

    Test and validate

    Make a call to your Plivo number using a regular mobile phone. Plivo will send a request to your Answer URL requesting for a valid XML response and process the call. Once Plivo receives the dial XML response, the call will be forwarded to the number defined in the XML. Meanwhile, the parameters listed in the XML Request - call status documentation will also be sent to your server.