go-zero尝试运行输出hello-world

参考文档

https://github.com/tal-tech/zero-doc/blob/main/doc/goctl.md

安装go-zero protoc goctl

这些参考文档即可安装成功

操作步骤

ZSH_THEME="bira"

╭─mac@macdeMacBook-Pro /www/go ‹master*› 
╰─$ cd /www/go
╭─mac@macdeMacBook-Pro /www/go ‹master*› 
╰─$ goctl api new hello 
╭─mac@macdeMacBook-Pro /www/go ‹master*› 
╰─$ cd hello  

此时的hello.api为

type Request {
	Name string `path:"name,options=you|me"`
}

type Response {
	Message string `json:"message"`
}

service hello-api {
	@handler HelloHandler
	get /from/:name(Request) returns (Response);
}

修改 为下面的

type HelloRequest {
	Name string `path:"name"`
}

type HelloResponse {
	Message string `json:"message"`
}

service hello-api {
	@handler HelloHandler
	get /hello/:name(HelloRequest) returns (HelloResponse);
}

执行命令重新生成

╭─mac@macdeMacBook-Pro /www/go/hello ‹master*› 
╰─$ goctl api go -api hello.api -dir .
etc/hello-api.yaml exists, ignored generation
internal/config/config.go exists, ignored generation
hello.go exists, ignored generation
internal/svc/servicecontext.go exists, ignored generation
internal/handler/hellohandler.go exists, ignored generation
internal/logic/hellologic.go exists, ignored generation
Done.

执行命令 go mod tidy 下载相关依赖

╭─mac@macdeMacBook-Pro /www/go/hello ‹master*› 
╰─$ go mod tidy                          
go: finding module for package github.com/tal-tech/go-zero/rest
go: finding module for package github.com/tal-tech/go-zero/core/logx
go: finding module for package github.com/tal-tech/go-zero/rest/httpx
go: finding module for package github.com/tal-tech/go-zero/core/conf
go: found github.com/tal-tech/go-zero/core/conf in github.com/tal-tech/go-zero v1.1.4

进入目录 internal/logic编辑hellologic.go

package logic

import (
	"context"

	"hello/internal/svc"
	"hello/internal/types"

	"github.com/tal-tech/go-zero/core/logx"
)

type HelloLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewHelloLogic(ctx context.Context, svcCtx *svc.ServiceContext) HelloLogic {
	return HelloLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *HelloLogic) Hello(req types.HelloRequest) (*types.HelloResponse, error) {
	// 新增的代码开始
	resp := types.HelloResponse{Message: req.Name}
	
	return &resp, nil
	// 新增的代码结束
}

hellohandle.go里面也有个Request要改为HelloRequest

因为我是把原来api两个request删了。估计是覆盖没覆盖成功

接下来运行

╭─mac@macdeMacBook-Pro /www/go/hello ‹master*› 
╰─$ go run hello.go -f etc/hello-api.yaml                                   2 ↵
Starting server at 0.0.0.0:8888..

此时浏览器访问 http://localhost:8888/hello/world

返回结果

{
message: "world"
}

输入其他的就返回什么

原文地址:https://www.cnblogs.com/brady-wang/p/14454361.html