2018-08-23 21:02:51 +02:00
|
|
|
// Package http provides the logic of the webserver
|
2017-05-17 16:14:32 +02:00
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2018-08-23 21:02:51 +02:00
|
|
|
// Read data from a http request via json format (input)
|
2017-05-17 16:14:32 +02:00
|
|
|
func Read(r *http.Request, to interface{}) (err error) {
|
|
|
|
if !strings.Contains(r.Header.Get("Content-Type"), "application/json") {
|
2018-03-22 22:10:05 +01:00
|
|
|
err = errors.New("no json request received")
|
2017-05-17 16:14:32 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
err = json.NewDecoder(r.Body).Decode(to)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-08-23 21:02:51 +02:00
|
|
|
// Write data as json to a http response (output)
|
2017-05-17 16:14:32 +02: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)
|
|
|
|
}
|