在使用micro的时候,使用给的例子greeter,服务启动后,再使用http访问发送请求,报错的
请求无参数返回报错
```
curl -XPOST -H 'Content-Type: application/json' -d '{}' http://localhost:8080/greeter/say/hello
{"id":"go.micro.api.greeter","code":400,"detail":"Name cannot be blank","status":"Bad Request"}
```
请求有参数返回报错
```
curl -XPOST -H 'Content-Type: application/json' -d '{"name": "John"}' http://localhost:8080/greeter/say/hello
{"id":"go.micro.api","code":500,"detail":"error during request: unknown field \"name\" in go_micro_api.Request","status":"Internal Server Error"}
```
网上找了很多,没有找到答
小白求解答
开启的服务
![WechatIMG9021.png](https://static.studygolang.com/190612/6d8fb166a665ce32e6b7e33227c48941.png)
greeter.api源码
```
package main
import (
"encoding/json"
"log"
"strings"
hello "github.com/micro/examples/greeter/srv/proto/hello"
"github.com/micro/go-micro"
"github.com/micro/go-micro/errors"
api "github.com/micro/micro/api/proto"
"context"
)
type Say struct {
Client hello.SayService
}
func (s *Say) Hello(ctx context.Context, req *api.Request, rsp *api.Response) error {
log.Print("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")
}
response, err := s.Client.Hello(ctx, &hello.Request{
Name: strings.Join(name.Values, " "),
})
if err != nil {
return err
}
rsp.StatusCode = 200
b, _ := json.Marshal(map[string]string{
"message": response.Msg,
})
rsp.Body = string(b)
return nil
}
func main() {
service := micro.NewService(
micro.Name("go.micro.api.greeter"),
)
// parse command line flags
service.Init()
service.Server().Handle(
service.Server().NewHandler(
&Say{Client: hello.NewSayService("go.micro.srv.greeter", service.Client())},
),
)
if err := service.Run(); err != nil {
log.Fatal(err)
}
}
```
找到原因了
我先是尝试 micro api --namespace=go.micro.srv 进行启动,可以正常请求
后来发现极有可能是因为handler配置的问题
于是按照micro api --handler=api,启动micro api
请求就正常了
![aaaa.png](https://static.studygolang.com/190612/9ab5c30290ebe82c8f9ac71e8725a6af.png)
#1