go-kratos 学习笔记(2) 创建api

proto 声明SayHi

先删除go.mod 从新初始化一下

复制代码
go mod init xgs_kratos

go mod tidy

编辑 api/helloword/v1/greeter.proto 新声明一个方法

复制代码
rpc SayHi (HelloHiRequest) returns (HelloHiReply) {
    option (google.api.http) = {
      post: "/hi"
      body: "*"
    };
  }

post请求的话 body必须写,定义好之后

复制代码
#执行
make api

#在执行
make generate

编辑service层

Go 复制代码
package service

import (
	"context"

	v1 "xgs_kratos/api/helloworld/v1"
	"xgs_kratos/internal/biz"
)

// GreeterService is a greeter service.
type GreeterService struct {
	v1.UnimplementedGreeterServer

	uc *biz.GreeterUsecase
}

// NewGreeterService new a greeter service.
func NewGreeterService(uc *biz.GreeterUsecase) *GreeterService {
	return &GreeterService{uc: uc}
}

// SayHello implements helloworld.GreeterServer.
func (s *GreeterService) SayHello(ctx context.Context, in *v1.HelloRequest) (*v1.HelloReply, error) {
	g, err := s.uc.CreateGreeter(ctx, &biz.Greeter{Hello: in.Name})
	if err != nil {
		return nil, err
	}
	return &v1.HelloReply{Message: "Hello " + g.Hello}, nil
}

// SayHi implements helloworld.GreeterServer.
func (s *GreeterService) SayHi(ctx context.Context, in *v1.HelloHiRequest) (*v1.HelloHiReply, error) {
	g, err := s.uc.CreateGreeter(ctx, &biz.Greeter{Hello: in.Name})
	if err != nil {
		return nil, err
	}
	return &v1.HelloHiReply{Message: "Hello " + g.Hello}, nil
}

运行 kratos run

postman请求的结果如下

项目的代码 码云 https://gitee.com/gebilaoxie/xgs_kratos.git

相关推荐
Linux-lucky8 小时前
21-Linux学习之旅之HTTPS和安全加固
linux·运维·学习·ubuntu·https
wp123_18 小时前
硬件元器件笔记|IPX8 防水 Type‑C 母座安费诺 124018802112A 与 TONEVEE TY48086‑24A 分析
c语言·开发语言·笔记
mifengxing9 小时前
操作系统 文件系统
笔记·操作系统·计算机408
学运维的Kysan10 小时前
暑假运维学习打卡第二十六天8.17
学习
无聊的菜鸟10 小时前
TMS320F2806X学习笔记(零)—— C2000、CCS、新建工程
笔记·mcu·c2000·f2806x
dear_bi_MyOnly10 小时前
AI人工智能分类识别——机器如何学习
人工智能·学习·分类
ljt272496066111 小时前
Compose笔记(八十三)--onVisibilityChanged
笔记
启雀AI13 小时前
培训平台移动端离线学习方案设计与实现:视频缓存、断点续传与进度同步的工程实践
android·学习·缓存·音视频·企业lms
Fa_Mian_Tuan15 小时前
图论基础|邻接矩阵超详细讲解(含无向/有向/带权图+完整可运行C语言代码)
c语言·数据结构·笔记·算法·图论
Bruce_Liuxiaowei15 小时前
从零到可运行:基于 Vue3 + FastAPI + DeepSeek-V3 的 AI 英语单词学习系统全栈实战
人工智能·python·学习·fastapi·全栈·智能体