本文整理匯總了Golang中github.com/micro/go-micro/client.NewRequest函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewRequest函數的具體用法?Golang NewRequest怎麽用?Golang NewRequest使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewRequest函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Query
// 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
}
示例2: pingPong
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)
}
}
示例3: Hello
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
}
示例4: Update
// 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
}
示例5: stream
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)
}
}
示例6: Pong
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
}
示例7: selector
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
}
示例8: call
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)
}
示例9: call
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)
}
示例10: requestEntity
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
}
示例11: call
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)
}
示例12: saveEntity
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
}
}
示例13: restHandler
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))
}
示例14: main
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)
}
示例15: Read
// 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
}