Skip to content

Instantly share code, notes, and snippets.

@agonzalezro
Created October 3, 2017 12:39
Show Gist options
  • Save agonzalezro/d68f7da0826d14b948f4f31b9254907b to your computer and use it in GitHub Desktop.
Save agonzalezro/d68f7da0826d14b948f4f31b9254907b to your computer and use it in GitHub Desktop.
hash: 26d5b8a8318cdb9b411e542057344c2142c5bd93d2a9b8962fb49188a5db0b65
updated: 2017-10-01T19:57:23.106136898+02:00
imports:
- name: github.com/gorilla/mux
version: 24fca303ac6da784b9e8269f724ddeb0b2eea5e7
- name: github.com/stretchr/testify
version: 69483b4bd14f5845b5a1e55bca19e954e827f1d0
testImports: []
package: github.com/agonzalezro/apiai-workshop-test
import:
- package: github.com/gorilla/mux
version: ~1.5.0
- package: github.com/stretchr/testify
version: ~1.1.4
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
)
type Request struct {
Result struct {
Parameters struct {
GivenName string `json:"given-name"`
}
}
}
type Response struct {
Speech string `json:"speech"`
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
var req Request
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
resp := Response{
Speech: "Hi " + req.Result.Parameters.GivenName,
}
bs, err := json.Marshal(resp)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
w.Write(bs)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
addr := ":8080"
log.Println("Listening on " + addr)
log.Println(http.ListenAndServe(addr, r))
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http/httptest"
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func payloadFromFixture(name string) ([]byte, error) {
path := fmt.Sprintf("fixtures/%s.json", name) // CAREFUL! Create your fixture in fixtures/xxx.json
f, err := os.Open(path)
if err != nil {
return nil, err
}
return ioutil.ReadAll(f)
}
func TestMyNameIsAlex(t *testing.T) {
assert := assert.New(t)
payload, err := payloadFromFixture("myNameIsAlex")
assert.NoError(err)
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/", bytes.NewReader(payload))
HomeHandler(w, r)
var resp Response
err = json.NewDecoder(w.Body).Decode(&resp)
assert.NoError(err)
assert.Equal(resp.Speech, "Hi Alex")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment