Esempio n. 1
0
func (*JSONPBResponseProcessor) Process(w http.ResponseWriter, model interface{}) error {
	msg := model.(proto.Message)
	w.Header().Set("Content-Type", "application/json")
	marshaler := jsonpb.Marshaler{}

	w.WriteHeader(http.StatusOK)
	marshaler.Marshal(w, msg)
	return nil
}
Esempio n. 2
0
func handleCollection(collection string, getFunc func(*http.Request) (interface{}, error)) {
	handleAPI(collection+"/", func(w http.ResponseWriter, r *http.Request) error {
		// Get the requested object.
		obj, err := getFunc(r)
		if err != nil {
			if err == topo.ErrNoNode {
				http.NotFound(w, r)
				return nil
			}
			return fmt.Errorf("can't get %v: %v", collection, err)
		}

		// JSON marshals a nil slice as "null", but we prefer "[]".
		if val := reflect.ValueOf(obj); val.Kind() == reflect.Slice && val.IsNil() {
			w.Header().Set("Content-Type", jsonContentType)
			w.Write([]byte("[]"))
			return nil
		}

		// JSON encode response.
		var data []byte
		switch obj := obj.(type) {
		case proto.Message:
			// We use jsonpb for protobuf messages because it is the only supported
			// way to marshal protobuf messages to JSON.
			// In addition to that, it's the only way to emit zero values in the JSON
			// output.
			// Unfortunately, it works only for protobuf messages. Therefore, we use
			// the default marshaler for the remaining structs (which are possibly
			// mixed protobuf and non-protobuf).
			// TODO(mberlin): Switch "EnumAsInts" to "false" once the frontend is
			//                updated and mixed types will use jsonpb as well.
			// Note: jsonpb may panic if the "proto.Message" is an embedded field
			// of "obj" and "obj" has non-exported fields.

			// Marshal the protobuf message.
			var b bytes.Buffer
			m := jsonpb.Marshaler{EnumsAsInts: true, EmitDefaults: true, Indent: "  ", OrigName: true}
			if err := m.Marshal(&b, obj); err != nil {
				return fmt.Errorf("jsonpb error: %v", err)
			}
			data = b.Bytes()
		default:
			data, err = json.MarshalIndent(obj, "", "  ")
			if err != nil {
				return fmt.Errorf("json error: %v", err)
			}
		}
		w.Header().Set("Content-Type", jsonContentType)
		w.Write(data)
		return nil
	})
}
Esempio n. 3
0
// Returns a valid json collection in bytes and the related jobs
func GetTestJSONCollectionBody(userId uint32, numberOfPayloads int) (*TrackBodyCollection, []*EventAction) {
	collection, wrongCollection, incompleteCollection := GetTestCollectionPairs(userId, numberOfPayloads)
	var collectionBytestream bytes.Buffer
	var disturbedCollectionBytestream bytes.Buffer
	var incompleteCollectionByteStream bytes.Buffer

	m := jsonpb.Marshaler{false, false, "", true}
	m.Marshal(&collectionBytestream, collection)
	m.Marshal(&disturbedCollectionBytestream, wrongCollection)
	m.Marshal(&incompleteCollectionByteStream, incompleteCollection)

	t := &TrackBodyCollection{
		collectionBytestream.Bytes(),
		disturbedCollectionBytestream.Bytes(),
		incompleteCollectionByteStream.Bytes()}
	return t, GetJobsFromCollection(collection)
}
Esempio n. 4
0
func testABEBulkCreate(t *testing.T) {
	count := 0
	r, w := io.Pipe()
	go func(w io.WriteCloser) {
		defer func() {
			if cerr := w.Close(); cerr != nil {
				t.Errorf("w.Close() failed with %v; want success", cerr)
			}
		}()
		for _, val := range []string{
			"foo", "bar", "baz", "qux", "quux",
		} {
			want := gw.ABitOfEverything{
				FloatValue:               1.5,
				DoubleValue:              2.5,
				Int64Value:               4294967296,
				Uint64Value:              9223372036854775807,
				Int32Value:               -2147483648,
				Fixed64Value:             9223372036854775807,
				Fixed32Value:             4294967295,
				BoolValue:                true,
				StringValue:              fmt.Sprintf("strprefix/%s", val),
				Uint32Value:              4294967295,
				Sfixed32Value:            2147483647,
				Sfixed64Value:            -4611686018427387904,
				Sint32Value:              2147483647,
				Sint64Value:              4611686018427387903,
				NonConventionalNameValue: "camelCase",

				Nested: []*gw.ABitOfEverything_Nested{
					{
						Name:   "hoge",
						Amount: 10,
					},
					{
						Name:   "fuga",
						Amount: 20,
					},
				},
			}
			var m jsonpb.Marshaler
			if err := m.Marshal(w, &want); err != nil {
				t.Fatalf("m.Marshal(%#v, w) failed with %v; want success", want, err)
			}
			if _, err := io.WriteString(w, "\n"); err != nil {
				t.Errorf("w.Write(%q) failed with %v; want success", "\n", err)
				return
			}
			count++
		}
	}(w)
	url := "http://localhost:8080/v1/example/a_bit_of_everything/bulk"
	resp, err := http.Post(url, "application/json", r)
	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 empty.Empty
	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 := resp.Header.Get("Grpc-Metadata-Count"), fmt.Sprintf("%d", count); got != want {
		t.Errorf("Grpc-Header-Count 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)
	}
}