-
Notifications
You must be signed in to change notification settings - Fork 22
/
resthandler.go
95 lines (69 loc) · 2.13 KB
/
resthandler.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package vcresthandler
import (
"errors"
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/hyperledger/aries-framework-go/spi/storage"
"github.com/trustbloc/logutil-go/pkg/log"
"github.com/trustbloc/sidetree-core-go/pkg/restapi/common"
logfields "github.com/trustbloc/orb/internal/pkg/log"
)
const idPathVariable = "id"
const (
statusNotFoundResponse = "Content Not Found."
internalServerErrorResponse = "Internal Server Error."
)
var logger = log.New("vc-rest-handler")
// Handler retrieves vc from verifiable credential store.
type Handler struct {
store storage.Store
}
// Path returns the HTTP REST endpoint for retrieving verifiable credential.
func (h *Handler) Path() string {
return fmt.Sprintf("/vc/{%s}", idPathVariable)
}
// Method returns the HTTP REST method for the verifiable credential.
func (h *Handler) Method() string {
return http.MethodGet
}
// Handler returns the HTTP REST handle for the Handler service.
func (h *Handler) Handler() common.HTTPRequestHandler {
return h.handle
}
// New returns a new Handler.
func New(vcStore storage.Store) *Handler {
h := &Handler{
store: vcStore,
}
return h
}
func (h *Handler) handle(w http.ResponseWriter, req *http.Request) {
id := mux.Vars(req)[idPathVariable]
vc, err := h.store.Get(id)
if err != nil {
if errors.Is(err, storage.ErrDataNotFound) {
logger.Debug("Verifiable credential not found", logfields.WithVerifiableCredentialID(id), log.WithError(err))
writeResponse(w, http.StatusNotFound, []byte(statusNotFoundResponse))
return
}
logger.Error("Error retrieving verifiable credential", logfields.WithVerifiableCredentialID(id), log.WithError(err))
writeResponse(w, http.StatusInternalServerError, []byte(internalServerErrorResponse))
return
}
writeResponse(w, http.StatusOK, vc)
}
func writeResponse(w http.ResponseWriter, status int, body []byte) {
w.WriteHeader(status)
if len(body) > 0 {
if _, err := w.Write(body); err != nil {
log.WriteResponseBodyError(logger, err)
return
}
log.WroteResponse(logger, body)
}
}