[TASK] add http io

This commit is contained in:
Martin Geno 2017-05-17 16:14:32 +02:00
parent 44f9087010
commit 17890122cf
No known key found for this signature in database
GPG Key ID: F0D39A37E925E941
2 changed files with 83 additions and 0 deletions

30
http/io.go Normal file
View File

@ -0,0 +1,30 @@
// Package that provides the logic of the webserver
package http
import (
"encoding/json"
"errors"
"net/http"
"strings"
)
// Function to read data from a http request via json format (input)
func Read(r *http.Request, to interface{}) (err error) {
if !strings.Contains(r.Header.Get("Content-Type"), "application/json") {
err = errors.New("no json request recieved")
return
}
err = json.NewDecoder(r.Body).Decode(to)
return
}
// Function to write data as json to a http response (output)
func Write(w http.ResponseWriter, data interface{}) {
js, err := json.Marshal(data)
if err != nil {
http.Error(w, "failed to encode response: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}

53
http/io_test.go Normal file
View File

@ -0,0 +1,53 @@
// Package that provides the logic of the webserver
package http
import (
"bytes"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
// Function to test write()
func TestWrite(t *testing.T) {
assert := assert.New(t)
w := httptest.NewRecorder()
from := map[string]string{"a": "b"}
Write(w, from)
result := w.Result()
assert.Equal([]string{"application/json"}, result.Header["Content-Type"], "no header information")
buf := new(bytes.Buffer)
buf.ReadFrom(result.Body)
to := buf.String()
assert.Equal("{\"a\":\"b\"}", to, "wrong content")
w = httptest.NewRecorder()
value := make(chan int)
Write(w, value)
result = w.Result()
assert.Equal(http.StatusInternalServerError, result.StatusCode, "wrong statuscode")
}
// Function to test read()
func TestRead(t *testing.T) {
assert := assert.New(t)
to := make(map[string]string)
r, _ := http.NewRequest("GET", "/a", strings.NewReader("{\"a\":\"b\"}"))
r.Header["Content-Type"] = []string{"application/json"}
err := Read(r, &to)
assert.NoError(err, "no error")
assert.Equal(map[string]string{"a": "b"}, to, "wrong content")
r.Header["Content-Type"] = []string{""}
err = Read(r, &to)
assert.Error(err, "no error")
}