Skip to content

Instantly share code, notes, and snippets.

@cdbkr
Last active August 29, 2015 14:10
Show Gist options
  • Save cdbkr/ddc0e9718ef9571c0387 to your computer and use it in GitHub Desktop.
Save cdbkr/ddc0e9718ef9571c0387 to your computer and use it in GitHub Desktop.
Go Bluemix Watson main
package main
//
// 1
//
import (
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
"encoding/json"
"encoding/base64"
"net/http"
"net/url"
"io/ioutil"
"bytes"
"fmt"
"os"
)
type Service struct {
...
}
type WatsonResponse struct {
...
}
type QuestionResponse struct{
QuestionResponse WatsonResponse
Error string
}
var(
service_url = "<service_url>"
service_username = "<service_username"
service_password = "<service_password>"
auth = ""
)
func main() {
//
// 2
//
servicesEnv := os.Getenv("VCAP_SERVICES");
appInfo := []byte(servicesEnv)
if len(appInfo) > 0{
var services map[string][]Service
err := json.Unmarshal(appInfo, &services)
if err != nil {
fmt.Printf("error %+v", err.Error())
//panic(err)
}else{
tempArrayServices := services["question_and_answer"];
if len(tempArrayServices) > 0{
tempCredentials := tempArrayServices[0].Credentials
service_url = tempCredentials.URL
service_username = tempCredentials.Username
service_password = tempCredentials.Password
}
}
authCredentials := fmt.Sprintf("%s:%s", service_username, service_password)
auth = fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(authCredentials)))
}
//
// 3
//
m := martini.Classic()
StaticOptions := martini.StaticOptions{Prefix: "public"}
m.Use(martini.Static("public", StaticOptions))
m.Use(render.Renderer(render.Options{
Directory: "templates", // Specify what path to load the templates from.
Layout: "layout", // Specify a layout template. Layouts can call {{ yield }} to render the current template.
Extensions: []string{".tmpl"}, // Specify extensions to load for templates.
Charset: "UTF-8", // Sets encoding for json and html content-types. Default is "UTF-8".
IndentJSON: true,
}))
m.Use(martini.Recovery())
m.Get("/", IndexRouter)
m.Post("/", PostReq)
m.Run()
}
//
// 4
//
func IndexRouter(r render.Render) {
r.HTML(200, "home/index", nil)
}
func PostReq(req *http.Request, r render.Render) {
responseObject := new(QuestionResponse)
parts := fmt.Sprintf("%s/v1/question/%s", service_url, req.FormValue("dataset"))
u, err := url.Parse(parts)
if err != nil {
panic(err)
}
jsonString := fmt.Sprintf(`{"question": {"evidenceRequest": {"items": 5 },"questionText": "%s"}}`, req.FormValue("questionText"));
//
/ 5
//
questionRequest, err := http.NewRequest("POST", parts,bytes.NewBuffer([]byte(jsonString)))
questionRequest.Host = u.Host
questionRequest.Header.Set("Content-Type", "application/json")
questionRequest.Header.Set("Accept", "application/json")
questionRequest.Header.Set("X-synctimeout", "30")
questionRequest.Header.Set("Authorization", auth)
client := &http.Client{}
resp, err := client.Do(questionRequest)
if err != nil {
responseObject.Error = string(err.Error())
r.HTML(200, "home/index", responseObject)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
questionResponseBody := []byte(body)
var questionAnswers []WatsonResponse
questionAnswers = make([]WatsonResponse,0)
errParseJson := json.Unmarshal(questionResponseBody, &questionAnswers)
if errParseJson != nil || len(questionAnswers) <= 0{
responseObject.Error = "Houston, we got a problem"
r.HTML(200, "home/index", responseObject)
}else{
responseObject.QuestionResponse = questionAnswers[0];
r.HTML(200, "home/index", responseObject)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment