-
Notifications
You must be signed in to change notification settings - Fork 0
/
updateResource.go
73 lines (64 loc) · 2.24 KB
/
updateResource.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
// ************************************************************************
// Copyright (C) 2022 plgd.dev, s.r.o.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ************************************************************************
package http
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"github.com/gorilla/mux"
"github.com/plgd-dev/go-coap/v2/message"
"github.com/plgd-dev/hub/v2/http-gateway/serverMux"
"github.com/plgd-dev/hub/v2/http-gateway/uri"
kitNetGrpc "github.com/plgd-dev/hub/v2/pkg/net/grpc"
"github.com/plgd-dev/hub/v2/resource-aggregate/commands"
"google.golang.org/grpc/codes"
"google.golang.org/protobuf/encoding/protojson"
)
func createContentBody(body io.ReadCloser) (io.ReadCloser, error) {
data, err := ioutil.ReadAll(body)
if err != nil {
return nil, fmt.Errorf("read body: %w", err)
}
req := commands.Content{
ContentType: message.AppJSON.String(),
CoapContentFormat: int32(message.AppJSON),
Data: data,
}
reqData, err := protojson.Marshal(&req)
if err != nil {
return nil, fmt.Errorf("cannot marshal to protojson: %w", err)
}
return ioutil.NopCloser(bytes.NewReader(reqData)), nil
}
func (requestHandler *RequestHandler) updateResource(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
deviceID := vars[uri.DeviceIDKey]
href := vars[uri.ResourceHrefKey]
contentType := r.Header.Get(uri.ContentTypeHeaderKey)
if contentType == uri.ApplicationProtoJsonContentType {
requestHandler.mux.ServeHTTP(w, r)
return
}
newBody, err := createContentBody(r.Body)
if err != nil {
serverMux.WriteError(w, kitNetGrpc.ForwardErrorf(codes.InvalidArgument, "cannot update resource('%v%v'): %v", deviceID, href, err))
return
}
r.Body = newBody
requestHandler.mux.ServeHTTP(w, r)
}