Notes/request_response.go

42 lines
762 B
Go
Raw Permalink Normal View History

2023-06-15 07:24:23 +02:00
package main
import (
2024-04-05 09:00:26 +02:00
// External
werr "git.gibonuddevalla.se/go/wrappederror"
2023-06-15 07:24:23 +02:00
// Standard
"encoding/json"
2023-06-16 07:11:27 +02:00
"io"
2023-06-15 14:12:35 +02:00
"net/http"
2023-06-15 07:24:23 +02:00
)
type Request struct {
ID string
}
2023-06-15 14:12:35 +02:00
func responseError(w http.ResponseWriter, err error) {
res := map[string]interface{}{
2023-06-17 09:11:14 +02:00
"OK": false,
"Error": err.Error(),
2023-06-15 14:12:35 +02:00
}
resJSON, _ := json.Marshal(res)
2024-04-05 09:00:26 +02:00
werr.Wrap(err).Log()
2023-06-15 14:12:35 +02:00
w.Header().Add("Content-Type", "application/json")
w.Write(resJSON)
}
func responseData(w http.ResponseWriter, data interface{}) {
resJSON, _ := json.Marshal(data)
w.Header().Add("Content-Type", "application/json")
w.Write(resJSON)
}
2023-06-16 07:11:27 +02:00
2023-06-17 09:11:14 +02:00
func parseRequest(r *http.Request, data interface{}) (err error) {
2023-06-16 07:11:27 +02:00
body, _ := io.ReadAll(r.Body)
defer r.Body.Close()
err = json.Unmarshal(body, data)
return
}