github.com/defanghe/fabric@v2.1.1+incompatible/internal/configtxlator/rest/protolator_handlers.go (about) 1 /* 2 Copyright IBM Corp. 2017 All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package rest 8 9 import ( 10 "bytes" 11 "fmt" 12 "io/ioutil" 13 "net/http" 14 "reflect" 15 16 "github.com/golang/protobuf/proto" 17 "github.com/gorilla/mux" 18 "github.com/hyperledger/fabric/common/tools/protolator" 19 ) 20 21 func getMsgType(r *http.Request) (proto.Message, error) { 22 vars := mux.Vars(r) 23 msgName := vars["msgName"] // Will not arrive is unset 24 25 msgType := proto.MessageType(msgName) 26 if msgType == nil { 27 return nil, fmt.Errorf("message name not found") 28 } 29 return reflect.New(msgType.Elem()).Interface().(proto.Message), nil 30 } 31 32 func Decode(w http.ResponseWriter, r *http.Request) { 33 msg, err := getMsgType(r) 34 if err != nil { 35 w.WriteHeader(http.StatusNotFound) 36 fmt.Fprintln(w, err) 37 return 38 } 39 40 buf, err := ioutil.ReadAll(r.Body) 41 if err != nil { 42 w.WriteHeader(http.StatusBadRequest) 43 fmt.Fprintln(w, err) 44 return 45 } 46 47 err = proto.Unmarshal(buf, msg) 48 if err != nil { 49 w.WriteHeader(http.StatusBadRequest) 50 fmt.Fprintln(w, err) 51 return 52 } 53 54 var buffer bytes.Buffer 55 err = protolator.DeepMarshalJSON(&buffer, msg) 56 if err != nil { 57 w.WriteHeader(http.StatusBadRequest) 58 fmt.Fprintln(w, err) 59 return 60 } 61 62 w.WriteHeader(http.StatusOK) 63 w.Header().Set("Content-Type", "application/json") 64 buffer.WriteTo(w) 65 } 66 67 func Encode(w http.ResponseWriter, r *http.Request) { 68 msg, err := getMsgType(r) 69 if err != nil { 70 w.WriteHeader(http.StatusNotFound) 71 fmt.Fprintln(w, err) 72 return 73 } 74 75 err = protolator.DeepUnmarshalJSON(r.Body, msg) 76 if err != nil { 77 w.WriteHeader(http.StatusBadRequest) 78 fmt.Fprintln(w, err) 79 return 80 } 81 82 data, err := proto.Marshal(msg) 83 if err != nil { 84 w.WriteHeader(http.StatusBadRequest) 85 fmt.Fprintln(w, err) 86 return 87 } 88 89 w.WriteHeader(http.StatusOK) 90 w.Header().Set("Content-Type", "application/octet-stream") 91 w.Write(data) 92 }