Example #1
0
// Query API handler
func (es *Elastic) Query(ctx context.Context, req *api.Request, rsp *api.Response) error {
	var err error
	var input map[string]interface{}
	var query []byte

	// Unmarshal unknown JSON
	if err = json.Unmarshal([]byte(req.Body), &input); err != nil {
		return errors.BadRequest("go.micro.api.elastic", err.Error())
	}

	query, err = json.Marshal(input["query"])

	srvReq := client.NewRequest(
		"go.micro.srv.elastic",
		"Elastic.Query",
		&elastic.QueryRequest{
			Index: fmt.Sprintf("%v", input["index"]),
			Type:  fmt.Sprintf("%v", input["type"]),
			Query: string(query),
		},
	)
	srvRsp := &elastic.SearchResponse{}
	if err = client.Call(ctx, srvReq, srvRsp); err != nil {
		return err
	}

	rsp.StatusCode = http.StatusOK
	rsp.Body = srvRsp.Result

	return nil
}
Example #2
0
func pingPong(i int) {
	// Create new request to service go.micro.srv.example, method Example.Call
	// Request can be empty as its actually ignored and merely used to call the handler
	req := client.NewRequest("go.micro.srv.example", "Example.PingPong", &example.StreamingRequest{})

	stream, err := client.Stream(context.Background(), req)
	if err != nil {
		fmt.Println("err:", err)
		return
	}

	for j := 0; j < i; j++ {
		if err := stream.Send(&example.Ping{Stroke: int64(j + 1)}); err != nil {
			fmt.Println("err:", err)
			return
		}
		rsp := &example.Pong{}
		err := stream.Recv(rsp)
		if err != nil {
			fmt.Println("recv err", err)
			break
		}
		fmt.Printf("Sent ping %v got pong %v\n", j+1, rsp.Stroke)
	}

	if stream.Error() != nil {
		fmt.Println("stream err:", err)
		return
	}

	if err := stream.Close(); err != nil {
		fmt.Println("stream close err:", err)
	}
}
Example #3
0
func (s *Say) Hello(ctx context.Context, req *api.Request, rsp *api.Response) error {
	log.Info("Received Say.Hello API request")

	name, ok := req.Get["name"]
	if !ok || len(name.Values) == 0 {
		return errors.BadRequest("go.micro.api.greeter", "Name cannot be blank")
	}

	request := client.NewRequest("go.micro.srv.greeter", "Say.Hello", &hello.Request{
		Name: strings.Join(name.Values, " "),
	})

	response := &hello.Response{}

	if err := client.Call(ctx, request, response); err != nil {
		return err
	}

	rsp.StatusCode = 200
	b, _ := json.Marshal(map[string]string{
		"message": response.Msg,
	})
	rsp.Body = string(b)

	return nil
}
Example #4
0
// Update API handler
func (es *Elastic) Update(ctx context.Context, req *api.Request, rsp *api.Response) error {
	var err error
	var input map[string]interface{}
	var data []byte

	// Unmarshal unknown JSON
	if err = json.Unmarshal([]byte(req.Body), &input); err != nil {
		return errors.BadRequest("go.micro.api.elastic", err.Error())
	}

	// Marshal unknown JSON (data)
	data, err = json.Marshal(input["data"])

	srvReq := client.NewRequest(
		"go.micro.srv.elastic",
		"Elastic.Update",
		&elastic.UpdateRequest{
			Index: fmt.Sprintf("%v", input["index"]),
			Type:  fmt.Sprintf("%v", input["type"]),
			Id:    fmt.Sprintf("%v", input["id"]),
			Data:  string(data),
		},
	)
	srvRsp := &elastic.UpdateResponse{}
	if err = client.Call(ctx, srvReq, srvRsp); err != nil {
		return err
	}

	rsp.StatusCode = http.StatusOK
	rsp.Body = `{}`

	return nil
}
Example #5
0
func stream(i int) {
	// Create new request to service go.micro.srv.example, method Example.Call
	// Request can be empty as its actually ignored and merely used to call the handler
	req := client.NewRequest("go.micro.srv.example", "Example.Stream", &example.StreamingRequest{})

	stream, err := client.Stream(context.Background(), req)
	if err != nil {
		fmt.Println("err:", err)
		return
	}
	if err := stream.Send(&example.StreamingRequest{Count: int64(i)}); err != nil {
		fmt.Println("err:", err)
		return
	}
	for stream.Error() == nil {
		rsp := &example.StreamingResponse{}
		err := stream.Recv(rsp)
		if err != nil {
			fmt.Println("recv err", err)
			break
		}
		fmt.Println("Stream: rsp:", rsp.Count)
	}

	if stream.Error() != nil {
		fmt.Println("stream err:", err)
		return
	}

	if err := stream.Close(); err != nil {
		fmt.Println("stream close err:", err)
	}
}
Example #6
0
func (p *Ping) Pong(ctx context.Context, req *proto.Ping, rsp *proto.Pong) error {
	rq := client.NewRequest("go.micro.srv.example", "Example.Call", &proto.Request{
		Name: "John",
	})

	rp := &proto.Response{}

	// Call service
	if err := client.Call(ctx, rq, rp); err != nil {
		return err
	}

	return nil
}
Example #7
0
func selector(id int, r router.Router) map[string]int {
	stats := make(map[string]int)

	// select the service
	next, err := r.Select(service)
	if err != nil {
		fmt.Println(id, "error selecting", err)
		return stats
	}

	for i := 1; i <= requests; i++ {
		// get a node
		node, err := next()
		if err != nil {
			fmt.Println(id, "error getting next", err)
			return stats
		}

		stats[node.Id]++

		// make some request
		// client.Call(foo, request)
		req := client.NewRequest(service, "Router.Stats", &proto.StatsRequest{})

		var dur time.Duration

		// lets set an error
		if d := (rand.Int() % i); d == 0 {
			dur = time.Millisecond * time.Duration(rand.Int()%20)
			err = errors.InternalServerError(service, "err")
		} else if d == 1 {
			dur = time.Second * 5
			err = errors.New(service, "timed out", 408)
		} else {
			dur = time.Millisecond * time.Duration(rand.Int()%10)
			err = nil
		}

		// mark the result
		r.Mark(service, node, err)

		// record timing
		r.Record(req, node, dur, err)

		//fmt.Println(id, "selected", node.Id)
		time.Sleep(time.Millisecond*10 + time.Duration(rand.Int()%10))
	}

	return stats
}
Example #8
0
func call(i int) {
	// Create new request to service go.micro.srv.example, method Example.Call
	req := client.NewRequest("go.micro.srv.example", "Ping.Pong", &example.Ping{
		Stroke: 10,
	})

	rsp := &example.Pong{}

	// Call service
	if err := client.Call(context.TODO(), req, rsp); err != nil {
		fmt.Println("call err: ", err, rsp)
		return
	}

	fmt.Println("Call:", i, "rsp:", rsp.Stroke)
}
Example #9
0
func call(i int) {
	// Create new request to service go.micro.srv.example, method Example.Call
	req := client.NewRequest("go.micro.srv.example", "Example.Call", &example.Request{
		Name: "John",
	})

	rsp := &example.Response{}

	// Call service
	if err := client.Call(context.Background(), req, rsp); err != nil {
		fmt.Println("call err: ", err, rsp)
		return
	}

	fmt.Println("Call:", i, "rsp:", rsp.Msg)
}
Example #10
0
func requestEntity(typ string, num int64, radius, lat, lon float64) ([]*common.Entity, error) {
	req := client.NewRequest("go.micro.srv.geo", "Location.Search", &loc.SearchRequest{
		Center: &common.Point{
			Latitude:  lat,
			Longitude: lon,
		},
		Type:        typ,
		Radius:      radius,
		NumEntities: num,
	})

	rsp := &loc.SearchResponse{}
	err := client.Call(context.Background(), req, rsp)
	if err != nil {
		return nil, err
	}
	return rsp.Entities, nil
}
Example #11
0
func call(i int) {
	// Create new request to service go.micro.srv.example, method Example.Call
	req := client.NewRequest("go.micro.srv.example", "Example.Call", &example.Request{
		Name: "John",
	})

	// create context with metadata
	ctx := c.WithMetadata(context.Background(), map[string]string{
		"datacenter": "local",
	})

	rsp := &example.Response{}

	// Call service
	if err := client.Call(ctx, req, rsp); err != nil {
		fmt.Println("call err: ", err, rsp)
		return
	}

	fmt.Println("Call:", i, "rsp:", rsp.Msg)
}
Example #12
0
func saveEntity(id, typ string, lat, lon float64) {
	entity := &common.Entity{
		Id:   id,
		Type: typ,
		Location: &common.Point{
			Latitude:  lat,
			Longitude: lon,
			Timestamp: time.Now().Unix(),
		},
	}

	req := client.NewRequest("go.micro.srv.geo", "Location.Save", &loc.SaveRequest{
		Entity: entity,
	})

	rsp := &loc.SaveResponse{}

	if err := client.Call(context.Background(), req, rsp); err != nil {
		fmt.Println(err)
		return
	}
}
Example #13
0
File: rest.go Project: kitech/micro
func restHandler(w http.ResponseWriter, r *http.Request) {
	request, err := requestToProto(r)
	if err != nil {
		er := errors.InternalServerError("go.micro.api", err.Error())
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(500)
		w.Write([]byte(er.Error()))
		return
	}

	service, method := pathToReceiver(r.URL.Path)
	req := client.NewRequest(service, method, request)
	rsp := &api.Response{}
	if err := client.Call(context.Background(), req, rsp); err != nil {
		w.Header().Set("Content-Type", "application/json")
		ce := errors.Parse(err.Error())
		switch ce.Code {
		case 0:
			w.WriteHeader(500)
		default:
			w.WriteHeader(int(ce.Code))
		}
		w.Write([]byte(ce.Error()))
		return
	}

	for _, header := range rsp.GetHeader() {
		for _, val := range header.Values {
			w.Header().Add(header.Key, val)
		}
	}

	if len(w.Header().Get("Content-Type")) == 0 {
		w.Header().Set("Content-Type", "application/json")
	}

	w.WriteHeader(int(rsp.StatusCode))
	w.Write([]byte(rsp.Body))
}
Example #14
0
func main() {

	// create an auth client
	a := auth.NewAuth(
		auth.Id("asim"),
		auth.Secret("foobar"),
	)

	// retreive a token
	t, err := a.Token()
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Printf("Retreived Token %+v\n", t)

	ctx := auth.ContextWithToken(context.TODO(), t)

	// introspect a token from context
	t, err = a.Introspect(ctx)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Printf("Introspected Token %+v\n", t)

	req := client.NewRequest("go.micro.example", "Example.Method", "request")

	// check if context/request is authorized
	t, err = a.Authorized(ctx, req)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Printf("Authorized Token %+v\n", t)
}
Example #15
0
// Read API handler
func (es *Elastic) Read(ctx context.Context, req *api.Request, rsp *api.Response) error {
	var err error
	var readRequest *elastic.ReadRequest

	if err = json.Unmarshal([]byte(req.Body), &readRequest); err != nil {
		return errors.InternalServerError("go.micro.api.elastic", err.Error())
	}

	srvReq := client.NewRequest(
		"go.micro.srv.elastic",
		"Elastic.Read",
		readRequest,
	)
	srvRsp := &elastic.ReadResponse{}
	if err = client.Call(ctx, srvReq, srvRsp); err != nil {
		return err
	}

	rsp.StatusCode = http.StatusOK
	rsp.Body = srvRsp.Result

	return nil
}
Example #16
0
func queryHealth(c *cli.Context) {
	if !c.Args().Present() {
		fmt.Println("require service name")
		return
	}
	service, err := registry.GetService(c.Args().First())
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	if service == nil || len(service) == 0 {
		fmt.Println("Service not found")
		return
	}
	req := client.NewRequest(service[0].Name, "Debug.Health", &health.Request{})
	fmt.Printf("service  %s\n\n", service[0].Name)
	for _, serv := range service {
		fmt.Println("\nversion ", serv.Version)
		fmt.Println("\nnode\t\taddress:port\t\tstatus")
		for _, node := range serv.Nodes {
			address := node.Address
			if node.Port > 0 {
				address = fmt.Sprintf("%s:%d", address, node.Port)
			}
			rsp := &health.Response{}
			err := client.CallRemote(context.Background(), address, req, rsp)
			var status string
			if err != nil {
				status = err.Error()
			} else {
				status = rsp.Status
			}
			fmt.Printf("%s\t\t%s:%d\t\t%s\n", node.Id, node.Address, node.Port, status)
		}
	}
}
Example #17
0
func main() {
	cmd.Init()

	// Create new request to service go.micro.srv.greeter, method Say.Hello
	req := client.NewRequest("go.micro.srv.greeter", "Say.Hello", &hello.Request{
		Name: "John",
	})

	// Set arbitrary headers in context
	ctx := metadata.NewContext(context.Background(), map[string]string{
		"X-User-Id": "john",
		"X-From-Id": "script",
	})

	rsp := &hello.Response{}

	// Call service
	if err := client.Call(ctx, req, rsp); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(rsp.Msg)
}