-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreateAndReturn.go
40 lines (38 loc) · 1 KB
/
createAndReturn.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package gohd
import (
"encoding/json"
"github.com/genstackio/goerror"
"github.com/genstackio/goerror/errors"
"net/http"
)
//goland:noinspection GoUnusedExportedFunction
func CreateAndReturn[T interface{}](w http.ResponseWriter, req *http.Request, worker func(*http.Request) (T, error)) {
result, err := worker(req)
if err != nil {
goerror.WriteError(w, err)
return
}
body, err := json.Marshal(result)
if nil != err {
goerror.WriteError(w, errors.MarshallError{Err: err})
return
}
statusCode := http.StatusCreated
contentType := "application/json;charset=utf-8"
if z, ok := any(result).(ResponseCompatible); ok {
forcedStatusCode := z.GetStatusCode()
if forcedStatusCode != 0 {
statusCode = forcedStatusCode
}
forcedContentType := z.GetContentType()
if "" != forcedContentType {
contentType = forcedContentType
}
}
w.Header().Set("Content-Type", contentType)
w.WriteHeader(statusCode)
_, err = w.Write(body)
if nil != err {
goerror.WriteError(w, errors.WriteError{Err: err})
}
}