func testABELookup(t *testing.T) { url := "http://localhost:8080/v1/example/a_bit_of_everything" cresp, err := http.Post(url, "application/json", strings.NewReader(` {"bool_value": true, "string_value": "strprefix/example"} `)) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", url, err) return } defer cresp.Body.Close() buf, err := ioutil.ReadAll(cresp.Body) if err != nil { t.Errorf("iotuil.ReadAll(cresp.Body) failed with %v; want success", err) return } if got, want := cresp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) return } var want gw.ABitOfEverything if err := jsonpb.UnmarshalString(string(buf), &want); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &want) failed with %v; want success", buf, err) return } url = fmt.Sprintf("%s/%s", url, want.Uuid) resp, err := http.Get(url) if err != nil { t.Errorf("http.Get(%q) failed with %v; want success", url, err) return } defer resp.Body.Close() buf, err = ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("ioutil.ReadAll(resp.Body) failed with %v; want success", err) return } var msg gw.ABitOfEverything if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) return } if got := msg; !reflect.DeepEqual(got, want) { t.Errorf("msg= %v; want %v", &got, &want) } if got, want := resp.Header.Get("Grpc-Metadata-Uuid"), want.Uuid; got != want { t.Errorf("Grpc-Metadata-Uuid was %s, wanted %s", got, want) } }
// MaybeExtractQ extracts proto from HTTP request and returns it. // Nil indicates failure, and appropriate status / description is written // to response. func MaybeExtractQ(w http.ResponseWriter, r *http.Request, defaultQ proto.Message) *proto.Message { q := proto.Clone(defaultQ) if r.Method == "POST" { reqBody, err := ioutil.ReadAll(r.Body) if err != nil { fmt.Fprintf(w, "Failed to read POST body %v", err) return nil } err = proto.Unmarshal(reqBody, q) if err != nil { fmt.Fprintf(w, "Failed to parse POST body as binary proto: %v", err) return nil } } else { err := r.ParseForm() if err != nil { http.NotFound(w, r) fmt.Fprintf(w, "strange query %v", err) return nil } pb := r.Form.Get("pb") if pb == "" { http.NotFound(w, r) fmt.Fprintf(w, "Non-empty jsonpb-encoded pb param required for GET") return nil } err = jsonpb.UnmarshalString(pb, q) if err != nil { fmt.Fprintf(w, "Failed to parse pb param %v", err) return nil } } return &q }
func decodeFrontendState(encodedFrontendState string) (*FrontendState, error) { var frontendState FrontendState if err := jsonpb.UnmarshalString(encodedFrontendState, &frontendState); err != nil { return nil, err } return &frontendState, nil }
func decodeServerRole(encodedServerRole string) (*proto.ServerRole, error) { var serverRole proto.ServerRole if err := jsonpb.UnmarshalString(encodedServerRole, &serverRole); err != nil { return nil, err } return &serverRole, nil }
func testEcho(t *testing.T, port int, contentType string) { url := fmt.Sprintf("http://localhost:%d/v1/example/echo/myid", port) resp, err := http.Post(url, "application/json", strings.NewReader("{}")) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", url, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("iotuil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } var msg gw.SimpleMessage if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) return } if got, want := msg.Id, "myid"; got != want { t.Errorf("msg.Id = %q; want %q", got, want) } if value := resp.Header.Get("Content-Type"); value != contentType { t.Errorf("Content-Type was %s, wanted %s", value, contentType) } }
func decodeServerState(encodedServerState string) (*ServerState, error) { var serverState ServerState if err := jsonpb.UnmarshalString(encodedServerState, &serverState); err != nil { return nil, err } return &serverState, nil }
func (n *OpenBazaarNode) Purchase(data *PurchaseData) error { // TODO: validate the purchase data is formatted properly contract := new(pb.RicardianContract) order := new(pb.Order) order.RefundAddress = n.Wallet.GetCurrentAddress(bitcoin.REFUND).EncodeAddress() order.Shipping.ShipTo = data.shipTo order.Shipping.Address = data.address order.Shipping.City = data.city order.Shipping.State = data.state order.Shipping.PostalCode = data.postalCode order.Shipping.Country = pb.CountryCode(pb.CountryCode_value[data.countryCode]) // TODO: Add blockchain ID to order order.BuyerID.Guid = n.IpfsNode.Identity.Pretty() pubkey, err := n.IpfsNode.PrivateKey.GetPublic().Bytes() if err != nil { return err } order.BuyerID.Pubkeys.Guid = pubkey order.BuyerID.Pubkeys.Bitcoin = n.Wallet.GetMasterPublicKey().Key order.Timestamp = uint64(time.Now().Unix()) for _, item := range data.items { i := new(pb.Order_Item) b, err := ipfs.Cat(n.Context, item.listingHash) if err != nil { return err } rc := new(pb.RicardianContract) err = jsonpb.UnmarshalString(string(b), rc) if err != nil { return err } // TODO: validate signatures on this contract before we purchase it contract.VendorListings = append(contract.VendorListings, rc.VendorListings[0]) contract.Signatures = append(contract.Signatures, rc.Signatures[0]) ser, err := proto.Marshal(rc.VendorListings[0]) if err != nil { return err } h := sha256.Sum256(ser) i.ListingHash = h[:] i.Quantity = uint32(item.quantity) for _, option := range item.options { o := new(pb.Order_Item_Option) o.Name = option.name o.Value = option.value i.Options = append(i.Options, o) } order.Items = append(order.Items, i) } // TODO: create payment obj // TODO: send to vendor return nil }
func main() { const input = `{"create_request": {"key": "Zm9v"}}` var protoReq etcdserverpb.WatchRequest if err := jsonpb.UnmarshalString(input, &protoReq); err != nil { log.Fatal(err) } fmt.Printf("success with %+v\n", protoReq.RequestUnion) }
func main() { const input = `{"key": "Zm9v", "type": "READ"}` var req WatchCreateRequest if err := jsonpb.UnmarshalString(input, &req); err != nil { log.Fatal(err) } fmt.Printf("success with %+v\n", req) // success with {Key:[102 111 111] Type:READ} }
func main() { const input = `{"create_request": {"key": "Zm9v"}}` var req WatchRequest if err := jsonpb.UnmarshalString(input, &req); err != nil { log.Fatal(err) // unknown field "create_request" in main.WatchRequest } fmt.Printf("success with %+v\n", req.RequestUnion) }
func testAdditionalBindings(t *testing.T) { for i, f := range []func() *http.Response{ func() *http.Response { url := "http://localhost:8080/v1/example/a_bit_of_everything/echo/hello" resp, err := http.Get(url) if err != nil { t.Errorf("http.Get(%q) failed with %v; want success", url, err) return nil } return resp }, func() *http.Response { url := "http://localhost:8080/v2/example/echo" resp, err := http.Post(url, "application/json", strings.NewReader(`"hello"`)) if err != nil { t.Errorf("http.Post(%q, %q, %q) failed with %v; want success", url, "application/json", `"hello"`, err) return nil } return resp }, func() *http.Response { url := "http://localhost:8080/v2/example/echo?value=hello" resp, err := http.Get(url) if err != nil { t.Errorf("http.Get(%q) failed with %v; want success", url, err) return nil } return resp }, } { resp := f() if resp == nil { continue } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("iotuil.ReadAll(resp.Body) failed with %v; want success; i=%d", err, i) return } if got, want := resp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d; i=%d", got, want, i) t.Logf("%s", buf) } var msg sub.StringMessage if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success; %d", buf, err, i) return } if got, want := msg.GetValue(), "hello"; got != want { t.Errorf("msg.GetValue() = %q; want %q", got, want) } } }
func MapToProto(in map[string]interface{}, pb proto.Message, idFix bool) { if idFix { if _, ok := in["_id"]; ok { in["id"] = in["_id"] delete(in, "_id") } } s, _ := json.Marshal(in) proto_json.UnmarshalString(string(s), pb) }
// ReadJSONBody reads the entire body of r and unmarshals it from JSON into msg. // If the request body is empty, no error is returned and msg is unchanged. func ReadJSONBody(r *http.Request, msg proto.Message) error { rec, err := ioutil.ReadAll(r.Body) if err != nil { return fmt.Errorf("body read error: %v", err) } if len(rec) == 0 { return nil } return jsonpb.UnmarshalString(string(rec), msg) }
func main() { const input = `{"key": "Zm9v", "type": "READ"}` // works with // const input = `{"key": "Zm9v", "type": 0}` var req WatchCreateRequest if err := jsonpb.UnmarshalString(input, &req); err != nil { log.Fatal(err) // unknown value "READ" for enum main.Type } fmt.Printf("success with %+v\n", req) }
func (c *rethinkClient) getMessageByID(term gorethink.Term, id string, message proto.Message) error { cursor, err := term.Get(id).ToJSON().Run(c.session) if err != nil { return err } data := "" if !cursor.Next(&data) { return cursor.Err() } if err := jsonpb.UnmarshalString(data, message); err != nil { return err } return nil }
func (a *rethinkAPIServer) getMessageByPrimaryKey(table Table, value interface{}, message proto.Message) error { cursor, err := a.getTerm(table).Get(value).Default(gorethink.Error("value not found")).ToJSON().Run(a.session) if err != nil { return err } data := "" if !cursor.Next(&data) { return cursor.Err() } if err := jsonpb.UnmarshalString(data, message); err != nil { return err } return nil }
func testABEList(t *testing.T) { url := "http://localhost:8080/v1/example/a_bit_of_everything" resp, err := http.Get(url) if err != nil { t.Errorf("http.Get(%q) failed with %v; want success", url, err) return } defer resp.Body.Close() dec := json.NewDecoder(resp.Body) var i int for i = 0; ; i++ { var item struct { Result json.RawMessage `json:"result"` Error map[string]interface{} `json:"error"` } err := dec.Decode(&item) if err == io.EOF { break } if err != nil { t.Errorf("dec.Decode(&item) failed with %v; want success; i = %d", err, i) } if len(item.Error) != 0 { t.Errorf("item.Error = %#v; want empty; i = %d", item.Error, i) continue } var msg gw.ABitOfEverything if err := jsonpb.UnmarshalString(string(item.Result), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", item.Result, err) } } if i <= 0 { t.Errorf("i == %d; want > 0", i) } value := resp.Header.Get("Grpc-Metadata-Count") if value == "" { t.Errorf("Grpc-Header-Count should not be empty") } count, err := strconv.Atoi(value) if err != nil { t.Errorf("failed to Atoi %q: %v", value, err) } if count <= 0 { t.Errorf("count == %d; want > 0", count) } }
func testABECreate(t *testing.T) { want := gw.ABitOfEverything{ FloatValue: 1.5, DoubleValue: 2.5, Int64Value: 4294967296, Uint64Value: 9223372036854775807, Int32Value: -2147483648, Fixed64Value: 9223372036854775807, Fixed32Value: 4294967295, BoolValue: true, StringValue: "strprefix/foo", Uint32Value: 4294967295, Sfixed32Value: 2147483647, Sfixed64Value: -4611686018427387904, Sint32Value: 2147483647, Sint64Value: 4611686018427387903, NonConventionalNameValue: "camelCase", } url := fmt.Sprintf("http://localhost:8080/v1/example/a_bit_of_everything/%f/%f/%d/separator/%d/%d/%d/%d/%v/%s/%d/%d/%d/%d/%d/%s", want.FloatValue, want.DoubleValue, want.Int64Value, want.Uint64Value, want.Int32Value, want.Fixed64Value, want.Fixed32Value, want.BoolValue, want.StringValue, want.Uint32Value, want.Sfixed32Value, want.Sfixed64Value, want.Sint32Value, want.Sint64Value, want.NonConventionalNameValue) resp, err := http.Post(url, "application/json", strings.NewReader("{}")) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", url, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("iotuil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } var msg gw.ABitOfEverything if err := jsonpb.UnmarshalString(string(buf), &msg); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) return } if msg.Uuid == "" { t.Error("msg.Uuid is empty; want not empty") } msg.Uuid = "" if got := msg; !reflect.DeepEqual(got, want) { t.Errorf("msg= %v; want %v", &got, &want) } }
func testEchoBody(t *testing.T) { sent := gw.SimpleMessage{Id: "example"} var m jsonpb.Marshaler payload, err := m.MarshalToString(&sent) if err != nil { t.Fatalf("m.MarshalToString(%#v) failed with %v; want success", payload, err) } url := "http://localhost:8080/v1/example/echo_body" resp, err := http.Post(url, "", strings.NewReader(payload)) if err != nil { t.Errorf("http.Post(%q) failed with %v; want success", url, err) return } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { t.Errorf("iotuil.ReadAll(resp.Body) failed with %v; want success", err) return } if got, want := resp.StatusCode, http.StatusOK; got != want { t.Errorf("resp.StatusCode = %d; want %d", got, want) t.Logf("%s", buf) } var received gw.SimpleMessage if err := jsonpb.UnmarshalString(string(buf), &received); err != nil { t.Errorf("jsonpb.UnmarshalString(%s, &msg) failed with %v; want success", buf, err) return } if got, want := received, sent; !reflect.DeepEqual(got, want) { t.Errorf("msg.Id = %q; want %q", got, want) } if got, want := resp.Header.Get("Grpc-Metadata-Foo"), "foo1"; got != want { t.Errorf("Grpc-Header-Foo was %q, wanted %q", got, want) } if got, want := resp.Header.Get("Grpc-Metadata-Bar"), "bar1"; got != want { t.Errorf("Grpc-Header-Bar was %q, wanted %q", got, want) } if got, want := resp.Trailer.Get("Grpc-Trailer-Foo"), "foo2"; got != want { t.Errorf("Grpc-Trailer-Foo was %q, wanted %q", got, want) } if got, want := resp.Trailer.Get("Grpc-Trailer-Bar"), "bar2"; got != want { t.Errorf("Grpc-Trailer-Bar was %q, wanted %q", got, want) } }
func (c *rethinkClient) GetPipelineRun(id string) (*pps.PipelineRun, error) { cursor, err := c.pipelineRuns.Get(id).ToJSON().Run(c.session) if err != nil { return nil, err } data := "" if !cursor.Next(&data) { return nil, cursor.Err() } var pipelineRun pps.PipelineRun if err := jsonpb.UnmarshalString(data, &pipelineRun); err != nil { return nil, err } return &pipelineRun, nil }
func (a *discoveryAddresser) getAddresses(version int64) (*proto.Addresses, error) { if version == InvalidVersion { return nil, fmt.Errorf("invalid version") } if addresses, ok := a.addresses[version]; ok { return addresses, nil } encodedAddresses, err := a.discoveryClient.Get(a.addressesKey(version)) if err != nil { return nil, err } var addresses proto.Addresses if err := jsonpb.UnmarshalString(encodedAddresses, &addresses); err != nil { return nil, err } return &addresses, nil }
func (c *rethinkClient) GetAllPipelineSources() ([]*pps.PipelineSource, error) { cursor, err := c.pipelineSources.ToJSON().Run(c.session) if err != nil { return nil, err } var pipelineSources []*pps.PipelineSource data := "" for cursor.Next(&data) { var pipelineSource pps.PipelineSource if err := jsonpb.UnmarshalString(data, &pipelineSource); err != nil { return nil, err } pipelineSources = append(pipelineSources, &pipelineSource) data = "" } return pipelineSources, cursor.Err() }
func processMultipleCursor( cursor *gorethink.Cursor, messageConstructor func() proto.Message, ) ([]interface{}, error) { var data []string if err := cursor.All(&data); err != nil { return nil, err } result := make([]interface{}, len(data)) for i, datum := range data { message := messageConstructor() if err := jsonpb.UnmarshalString(datum, message); err != nil { return nil, err } result[i] = message } return result, nil }
func (c *rethinkClient) GetPipelineRunStatusLatest(id string) (*pps.PipelineRunStatus, error) { cursor, err := c.statuses. GetAllByIndex("pipeline_run_id", id). OrderBy(gorethink.Desc("timestamp")). Nth(0). ToJSON(). Run(c.session) if err != nil { return nil, err } data := "" if !cursor.Next(&data) { return nil, cursor.Err() } var pipelineRunStatus pps.PipelineRunStatus if err := jsonpb.UnmarshalString(data, &pipelineRunStatus); err != nil { return nil, err } return &pipelineRunStatus, nil }
func (c *rethinkClient) GetAllPipelineRunStatuses(pipelineRunID string) ([]*pps.PipelineRunStatus, error) { cursor, err := c.pipelineRunStatuses. GetAllByIndex("pipeline_run_id", pipelineRunID). OrderBy(gorethink.Desc("timestamp")). Without("id"). Map(rethinkToJSON). Run(c.session) if err != nil { return nil, err } var pipelineRunStatuses []*pps.PipelineRunStatus data := "" for cursor.Next(&data) { var pipelineRunStatus pps.PipelineRunStatus if err := jsonpb.UnmarshalString(data, &pipelineRunStatus); err != nil { return nil, err } pipelineRunStatuses = append(pipelineRunStatuses, &pipelineRunStatus) } return pipelineRunStatuses, cursor.Err() }
// Call sends req to the given server method as a JSON-encoded body and // unmarshals the response body as JSON into reply. func Call(server, method string, req, reply proto.Message) error { body := new(bytes.Buffer) if err := JSONMarshaler.Marshal(body, req); err != nil { return fmt.Errorf("error marshaling %T: %v", req, err) } resp, err := http.Post(strings.TrimSuffix(server, "/")+"/"+strings.Trim(method, "/"), jsonBodyType, body) if err != nil { return fmt.Errorf("http error: %v", err) } rec, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { return fmt.Errorf("error reading response body: %v", err) } else if resp.StatusCode != http.StatusOK { return fmt.Errorf("remote method error (code %d): %s", resp.StatusCode, string(rec)) } if err := jsonpb.UnmarshalString(string(rec), reply); err != nil { return fmt.Errorf("error unmarshaling %T: %v", reply, err) } return nil }
func (this *htmlProto2) Produce(w net_http.ResponseWriter, req *net_http.Request) { w.Write([]byte(Header(`Proto2`, `Produce`))) jsonString := req.FormValue("json") someValue := false msg := &Album{} if len(jsonString) > 0 { err := github_com_golang_protobuf_jsonpb.UnmarshalString(jsonString, msg) if err != nil { if err != io.EOF { w.Write([]byte("<div class=\"alert alert-danger\" role=\"alert\">" + err.Error() + "</div>")) return } w.Write([]byte("<div class=\"alert alert-danger\" role=\"alert\">" + err.Error() + "</div>")) } someValue = true } w.Write([]byte(FormProto2_Produce)) if someValue { reply, err := this.client.Produce(golang_org_x_net_context.Background(), msg) if err != nil { if err != io.EOF { w.Write([]byte("<div class=\"alert alert-danger\" role=\"alert\">" + err.Error() + "</div>")) return } w.Write([]byte("<div class=\"alert alert-danger\" role=\"alert\">" + err.Error() + "</div>")) } out, err := this.stringer(msg, reply) if err != nil { if err != io.EOF { w.Write([]byte("<div class=\"alert alert-danger\" role=\"alert\">" + err.Error() + "</div>")) return } w.Write([]byte("<div class=\"alert alert-danger\" role=\"alert\">" + err.Error() + "</div>")) } w.Write(out) } w.Write([]byte(Footer)) }
func (c *rethinkClient) GetPipelineRunLogs(pipelineRunID string) ([]*pps.PipelineRunLog, error) { cursor, err := c.pipelineLogs. GetAllByIndex("pipeline_run_id", pipelineRunID). Map(func(row gorethink.Term) interface{} { return row.ToJSON() }).Run(c.session) if err != nil { return nil, err } var pipelineLogs []string if err := cursor.All(&pipelineLogs); err != nil { return nil, err } var result []*pps.PipelineRunLog for _, data := range pipelineLogs { var pipelineLog pps.PipelineRunLog if err := jsonpb.UnmarshalString(data, &pipelineLog); err != nil { return nil, err } result = append(result, &pipelineLog) } return result, nil }
func (c *rethinkClient) GetPipelineRunContainers(pipelineRunID string) ([]*pps.PipelineRunContainer, error) { cursor, err := c.pipelineContainers. GetAllByIndex("pipeline_run_id", pipelineRunID). Without("id"). Map(rethinkToJSON). Run(c.session) if err != nil { return nil, err } var pipelineRunContainers []string if err := cursor.All(&pipelineRunContainers); err != nil { return nil, err } var result []*pps.PipelineRunContainer for _, data := range pipelineRunContainers { var pipelineRunContainer pps.PipelineRunContainer if err := jsonpb.UnmarshalString(data, &pipelineRunContainer); err != nil { return nil, err } result = append(result, &pipelineRunContainer) } return result, nil }
func (a *sharder) getAddresses(version int64) (*Addresses, error) { if version == InvalidVersion { return nil, fmt.Errorf("invalid version") } a.addressesLock.RLock() if addresses, ok := a.addresses[version]; ok { a.addressesLock.RUnlock() return addresses, nil } a.addressesLock.RUnlock() a.addressesLock.Lock() defer a.addressesLock.Unlock() encodedAddresses, err := a.discoveryClient.Get(a.addressesKey(version)) if err != nil { return nil, err } var addresses Addresses if err := jsonpb.UnmarshalString(encodedAddresses, &addresses); err != nil { return nil, err } a.addresses[version] = &addresses return &addresses, nil }