github.com/defanghe/fabric@v2.1.1+incompatible/internal/configtxlator/rest/configtxlator_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 "fmt" 11 "io/ioutil" 12 "net/http" 13 14 "github.com/golang/protobuf/proto" 15 cb "github.com/hyperledger/fabric-protos-go/common" 16 "github.com/hyperledger/fabric/internal/configtxlator/update" 17 ) 18 19 func fieldBytes(fieldName string, r *http.Request) ([]byte, error) { 20 fieldFile, _, err := r.FormFile(fieldName) 21 if err != nil { 22 return nil, err 23 } 24 defer fieldFile.Close() 25 26 return ioutil.ReadAll(fieldFile) 27 } 28 29 func fieldConfigProto(fieldName string, r *http.Request) (*cb.Config, error) { 30 fieldBytes, err := fieldBytes(fieldName, r) 31 if err != nil { 32 return nil, fmt.Errorf("error reading field bytes: %s", err) 33 } 34 35 config := &cb.Config{} 36 err = proto.Unmarshal(fieldBytes, config) 37 if err != nil { 38 return nil, fmt.Errorf("error unmarshaling field bytes: %s", err) 39 } 40 41 return config, nil 42 } 43 44 func ComputeUpdateFromConfigs(w http.ResponseWriter, r *http.Request) { 45 originalConfig, err := fieldConfigProto("original", r) 46 if err != nil { 47 w.WriteHeader(http.StatusBadRequest) 48 fmt.Fprintf(w, "Error with field 'original': %s\n", err) 49 return 50 } 51 52 updatedConfig, err := fieldConfigProto("updated", r) 53 if err != nil { 54 w.WriteHeader(http.StatusBadRequest) 55 fmt.Fprintf(w, "Error with field 'updated': %s\n", err) 56 return 57 } 58 59 configUpdate, err := update.Compute(originalConfig, updatedConfig) 60 if err != nil { 61 w.WriteHeader(http.StatusBadRequest) 62 fmt.Fprintf(w, "Error computing update: %s\n", err) 63 return 64 } 65 66 configUpdate.ChannelId = r.FormValue("channel") 67 68 encoded, err := proto.Marshal(configUpdate) 69 if err != nil { 70 w.WriteHeader(http.StatusInternalServerError) 71 fmt.Fprintf(w, "Error marshaling config update: %s\n", err) 72 return 73 } 74 75 w.WriteHeader(http.StatusOK) 76 w.Header().Set("Content-Type", "application/octet-stream") 77 w.Write(encoded) 78 }