genofire/hs_monolith
genofire
/
hs_monolith
Archived
1
0
Fork 0
This repository has been archived on 2020-09-27. You can view files and clone it, but cannot push or open issues or pull requests.
hs_monolith/lib/http/io.go

32 lines
819 B
Go
Raw Normal View History

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