This repository has been archived by the owner on Apr 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
rest.go
68 lines (53 loc) · 1.57 KB
/
rest.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
// Package rest provides rest operation.
package rest
import (
"encoding/json"
"io"
"net/http"
"github.com/hyperledger/aries-framework-go/pkg/common/log"
"github.com/trustbloc/agent-sdk/pkg/controller/command"
)
var logger = log.New("agent-sdk/rest")
// Handler http handler for each controller API endpoint.
type Handler interface {
Path() string
Method() string
Handle() http.HandlerFunc
}
// Execute executes given command with args provided and writes error to
// response writer.
func Execute(exec command.Exec, rw http.ResponseWriter, req io.Reader) {
rw.Header().Set("Content-Type", "application/json")
err := exec(rw, req)
if err != nil {
SendError(rw, err)
}
}
type genericErrorBody struct {
Code command.Code `json:"code"`
Message string `json:"message"`
}
// SendError sends command error as http response in generic error format.
func SendError(rw http.ResponseWriter, err command.Error) {
var status int
status = http.StatusInternalServerError
if err.Type() == command.ValidationError {
status = http.StatusBadRequest
}
SendHTTPStatusError(rw, status, err.Code(), err)
}
// SendHTTPStatusError sends given http status code to response with error body.
func SendHTTPStatusError(rw http.ResponseWriter, httpStatus int, code command.Code, err error) {
rw.WriteHeader(httpStatus)
e := json.NewEncoder(rw).Encode(genericErrorBody{
Code: code,
Message: err.Error(),
})
if e != nil {
logger.Errorf("Unable to send error response, %s", e)
}
}