Last active
May 2, 2016 10:07
-
-
Save IndianGuru/763ed8bfbc871cae30d7838236fc4775 to your computer and use it in GitHub Desktop.
Go program that uses the api.ai service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"log" | |
"net/http" | |
"time" | |
) | |
type QResponse struct { | |
ID string `json:"id"` | |
Timestamp time.Time `json:"timestamp"` | |
Result struct { | |
Source string `json:"source"` | |
ResolvedQuery string `json:"resolvedQuery"` | |
Action string `json:"action"` | |
ActionIncomplete bool `json:"actionIncomplete"` | |
Parameters struct { | |
Name string `json:"name"` | |
} `json:"parameters"` | |
Contexts []struct { | |
Name string `json:"name"` | |
Parameters struct { | |
Name string `json:"name"` | |
} `json:"parameters"` | |
Lifespan int `json:"lifespan"` | |
} `json:"contexts"` | |
Metadata struct { | |
IntentID string `json:"intentId"` | |
IntentName string `json:"intentName"` | |
} `json:"metadata"` | |
Fulfillment struct { | |
Speech string `json:"speech"` | |
} `json:"fulfillment"` | |
} `json:"result"` | |
Status struct { | |
Code int `json:"code"` | |
ErrorType string `json:"errorType"` | |
} `json:"status"` | |
} | |
func main() { | |
url := fmt.Sprintf("https://api.api.ai/v1/query?v=20150910&query=weather&lang=en&latitude=35.925&longitude=-86.8688889&sessionId=1234567890") | |
// Build the request | |
req, err := http.NewRequest("GET", url, nil) | |
if err != nil { | |
log.Fatal("NewRequest: ", err) | |
return | |
} | |
// Replace 9ea93023b7274cfbb392b289658cff0b by your Client access token | |
req.Header.Add("Authorization", "Bearer 9ea93023b7274cfbb392b289658cff0b") | |
// For control over HTTP client headers, | |
// redirect policy, and other settings, | |
// create a Client | |
// A Client is an HTTP client | |
client := &http.Client{} | |
// Send the request via a client | |
// Do sends an HTTP request and | |
// returns an HTTP response | |
resp, err := client.Do(req) | |
if err != nil { | |
log.Fatal("Do: ", err) | |
return | |
} | |
// Callers should close resp.Body | |
// when done reading from it | |
// Defer the closing of the body | |
defer resp.Body.Close() | |
// Fill the record with the data from the JSON | |
var record QResponse | |
// Use json.Decode for reading streams of JSON data | |
if err := json.NewDecoder(resp.Body).Decode(&record); err != nil { | |
log.Println(err) | |
} | |
fmt.Println("Status = ", record.Status.Code) | |
fmt.Println("Response = ", record.Result.Fulfillment.Speech) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment