2017-05-03 07:16:45 +02:00
|
|
|
// Package that provides the logic of the webserver
|
2017-03-30 15:36:04 +02:00
|
|
|
package http
|
2017-03-25 16:09:17 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"net/http"
|
2017-05-12 10:17:27 +02:00
|
|
|
"strings"
|
2017-03-25 16:09:17 +01:00
|
|
|
)
|
|
|
|
|
2017-05-03 07:16:45 +02:00
|
|
|
// Function to read data from a http request via json format (input)
|
2017-03-25 16:09:17 +01:00
|
|
|
func Read(r *http.Request, to interface{}) (err error) {
|
2017-05-12 10:17:27 +02:00
|
|
|
if !strings.Contains(r.Header.Get("Content-Type"), "application/json") {
|
|
|
|
err = errors.New("no json request recieved")
|
2017-03-25 16:09:17 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
err = json.NewDecoder(r.Body).Decode(to)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-05-03 07:16:45 +02:00
|
|
|
// Function to write data as json to a http response (output)
|
2017-03-25 16:09:17 +01:00
|
|
|
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)
|
2017-04-28 10:27:36 +02:00
|
|
|
}
|