feat(api): 初始化API项目结构

- 创建基础API服务框架
- 配置路由和请求处理逻辑
- 添加配置文件支持
- 实现基本的HTTP服务启动功能
- 生成API接口定义文件
- 初始化模块依赖管理文件
- 创建服务上下文管理器
- 定义请求响应数据结构
- 添加类型转换和解析逻辑
- 实现基础中间件支持
- 集成日志记录组件
- 提供默认错误处理机制
- 添加JSON序列化支持
- 实现路径参数校验功能
This commit is contained in:
huanglei19951029 2025-12-09 17:37:21 +08:00
parent 7b867701c0
commit 5e6509e9e1
21 changed files with 658 additions and 0 deletions

15
api/api.api Normal file
View File

@ -0,0 +1,15 @@
syntax = "v1"
type Request {
Name string `path:"name,options=you|me"`
}
type Response {
Message string `json:"message"`
}
service api-api {
@handler ApiHandler
get /from/:name (Request) returns (Response)
}

34
api/api.go Normal file
View File

@ -0,0 +1,34 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package main
import (
"flag"
"fmt"
"mingyang-admin-pay/api/internal/config"
"mingyang-admin-pay/api/internal/handler"
"mingyang-admin-pay/api/internal/svc"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/rest"
)
var configFile = flag.String("f", "etc/api-api.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
server := rest.MustNewServer(c.RestConf)
defer server.Stop()
ctx := svc.NewServiceContext(c)
handler.RegisterHandlers(server, ctx)
fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
server.Start()
}

3
api/etc/api-api.yaml Normal file
View File

@ -0,0 +1,3 @@
Name: api-api
Host: 0.0.0.0
Port: 8888

3
api/go.mod Normal file
View File

@ -0,0 +1,3 @@
module mingyang-admin-pay/api
go 1.25.3

View File

@ -0,0 +1,10 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package config
import "github.com/zeromicro/go-zero/rest"
type Config struct {
rest.RestConf
}

View File

@ -0,0 +1,31 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package handler
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"mingyang-admin-pay/api/internal/logic"
"mingyang-admin-pay/api/internal/svc"
"mingyang-admin-pay/api/internal/types"
)
func ApiHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.Request
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := logic.NewApiLogic(r.Context(), svcCtx)
resp, err := l.Api(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}

View File

@ -0,0 +1,24 @@
// Code generated by goctl. DO NOT EDIT.
// goctl 1.9.2
package handler
import (
"net/http"
"mingyang-admin-pay/api/internal/svc"
"github.com/zeromicro/go-zero/rest"
)
func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes(
[]rest.Route{
{
Method: http.MethodGet,
Path: "/from/:name",
Handler: ApiHandler(serverCtx),
},
},
)
}

View File

@ -0,0 +1,33 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package logic
import (
"context"
"mingyang-admin-pay/api/internal/svc"
"mingyang-admin-pay/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type ApiLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewApiLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ApiLogic {
return &ApiLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *ApiLogic) Api(req *types.Request) (resp *types.Response, err error) {
// todo: add your logic here and delete this line
return
}

View File

@ -0,0 +1,18 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package svc
import (
"mingyang-admin-pay/api/internal/config"
)
type ServiceContext struct {
Config config.Config
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
}
}

View File

@ -0,0 +1,12 @@
// Code generated by goctl. DO NOT EDIT.
// goctl 1.9.2
package types
type Request struct {
Name string `path:"name,options=you|me"`
}
type Response struct {
Message string `json:"message"`
}

6
rpc/etc/rpc.yaml Normal file
View File

@ -0,0 +1,6 @@
Name: rpc.rpc
ListenOn: 0.0.0.0:8080
Etcd:
Hosts:
- 127.0.0.1:2379
Key: rpc.rpc

3
rpc/go.mod Normal file
View File

@ -0,0 +1,3 @@
module mingyang-admin-pay/rpc
go 1.25.3

View File

@ -0,0 +1,7 @@
package config
import "github.com/zeromicro/go-zero/zrpc"
type Config struct {
zrpc.RpcServerConf
}

View File

@ -0,0 +1,30 @@
package logic
import (
"context"
"mingyang-admin-pay/rpc/internal/svc"
"mingyang-admin-pay/rpc/rpc"
"github.com/zeromicro/go-zero/core/logx"
)
type PingLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewPingLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PingLogic {
return &PingLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *PingLogic) Ping(in *rpc.Request) (*rpc.Response, error) {
// todo: add your logic here and delete this line
return &rpc.Response{}, nil
}

View File

@ -0,0 +1,29 @@
// Code generated by goctl. DO NOT EDIT.
// goctl 1.9.2
// Source: rpc.proto
package server
import (
"context"
"mingyang-admin-pay/rpc/internal/logic"
"mingyang-admin-pay/rpc/internal/svc"
"mingyang-admin-pay/rpc/rpc"
)
type RpcServer struct {
svcCtx *svc.ServiceContext
rpc.UnimplementedRpcServer
}
func NewRpcServer(svcCtx *svc.ServiceContext) *RpcServer {
return &RpcServer{
svcCtx: svcCtx,
}
}
func (s *RpcServer) Ping(ctx context.Context, in *rpc.Request) (*rpc.Response, error) {
l := logic.NewPingLogic(ctx, s.svcCtx)
return l.Ping(in)
}

View File

@ -0,0 +1,13 @@
package svc
import "mingyang-admin-pay/rpc/internal/config"
type ServiceContext struct {
Config config.Config
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
}
}

39
rpc/rpc.go Normal file
View File

@ -0,0 +1,39 @@
package main
import (
"flag"
"fmt"
"mingyang-admin-pay/rpc/internal/config"
"mingyang-admin-pay/rpc/internal/server"
"mingyang-admin-pay/rpc/internal/svc"
"mingyang-admin-pay/rpc/rpc"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/service"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
var configFile = flag.String("f", "etc/rpc.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
ctx := svc.NewServiceContext(c)
s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
rpc.RegisterRpcServer(grpcServer, server.NewRpcServer(ctx))
if c.Mode == service.DevMode || c.Mode == service.TestMode {
reflection.Register(grpcServer)
}
})
defer s.Stop()
fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
s.Start()
}

16
rpc/rpc.proto Normal file
View File

@ -0,0 +1,16 @@
syntax = "proto3";
package rpc;
option go_package="./rpc";
message Request {
string ping = 1;
}
message Response {
string pong = 1;
}
service Rpc {
rpc Ping(Request) returns(Response);
}

173
rpc/rpc/rpc.pb.go Normal file
View File

@ -0,0 +1,173 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.10
// protoc v3.21.11
// source: rpc.proto
package rpc
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Request struct {
state protoimpl.MessageState `protogen:"open.v1"`
Ping string `protobuf:"bytes,1,opt,name=ping,proto3" json:"ping,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Request) Reset() {
*x = Request{}
mi := &file_rpc_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Request) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Request) ProtoMessage() {}
func (x *Request) ProtoReflect() protoreflect.Message {
mi := &file_rpc_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Request.ProtoReflect.Descriptor instead.
func (*Request) Descriptor() ([]byte, []int) {
return file_rpc_proto_rawDescGZIP(), []int{0}
}
func (x *Request) GetPing() string {
if x != nil {
return x.Ping
}
return ""
}
type Response struct {
state protoimpl.MessageState `protogen:"open.v1"`
Pong string `protobuf:"bytes,1,opt,name=pong,proto3" json:"pong,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Response) Reset() {
*x = Response{}
mi := &file_rpc_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Response) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Response) ProtoMessage() {}
func (x *Response) ProtoReflect() protoreflect.Message {
mi := &file_rpc_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Response.ProtoReflect.Descriptor instead.
func (*Response) Descriptor() ([]byte, []int) {
return file_rpc_proto_rawDescGZIP(), []int{1}
}
func (x *Response) GetPong() string {
if x != nil {
return x.Pong
}
return ""
}
var File_rpc_proto protoreflect.FileDescriptor
const file_rpc_proto_rawDesc = "" +
"\n" +
"\trpc.proto\x12\x03rpc\"\x1d\n" +
"\aRequest\x12\x12\n" +
"\x04ping\x18\x01 \x01(\tR\x04ping\"\x1e\n" +
"\bResponse\x12\x12\n" +
"\x04pong\x18\x01 \x01(\tR\x04pong2*\n" +
"\x03Rpc\x12#\n" +
"\x04Ping\x12\f.rpc.Request\x1a\r.rpc.ResponseB\aZ\x05./rpcb\x06proto3"
var (
file_rpc_proto_rawDescOnce sync.Once
file_rpc_proto_rawDescData []byte
)
func file_rpc_proto_rawDescGZIP() []byte {
file_rpc_proto_rawDescOnce.Do(func() {
file_rpc_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_rpc_proto_rawDesc), len(file_rpc_proto_rawDesc)))
})
return file_rpc_proto_rawDescData
}
var file_rpc_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_rpc_proto_goTypes = []any{
(*Request)(nil), // 0: rpc.Request
(*Response)(nil), // 1: rpc.Response
}
var file_rpc_proto_depIdxs = []int32{
0, // 0: rpc.Rpc.Ping:input_type -> rpc.Request
1, // 1: rpc.Rpc.Ping:output_type -> rpc.Response
1, // [1:2] is the sub-list for method output_type
0, // [0:1] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_rpc_proto_init() }
func file_rpc_proto_init() {
if File_rpc_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_rpc_proto_rawDesc), len(file_rpc_proto_rawDesc)),
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_rpc_proto_goTypes,
DependencyIndexes: file_rpc_proto_depIdxs,
MessageInfos: file_rpc_proto_msgTypes,
}.Build()
File_rpc_proto = out.File
file_rpc_proto_goTypes = nil
file_rpc_proto_depIdxs = nil
}

121
rpc/rpc/rpc_grpc.pb.go Normal file
View File

@ -0,0 +1,121 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.0
// - protoc v3.21.11
// source: rpc.proto
package rpc
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
Rpc_Ping_FullMethodName = "/rpc.Rpc/Ping"
)
// RpcClient is the client API for Rpc service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type RpcClient interface {
Ping(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error)
}
type rpcClient struct {
cc grpc.ClientConnInterface
}
func NewRpcClient(cc grpc.ClientConnInterface) RpcClient {
return &rpcClient{cc}
}
func (c *rpcClient) Ping(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(Response)
err := c.cc.Invoke(ctx, Rpc_Ping_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// RpcServer is the server API for Rpc service.
// All implementations must embed UnimplementedRpcServer
// for forward compatibility.
type RpcServer interface {
Ping(context.Context, *Request) (*Response, error)
mustEmbedUnimplementedRpcServer()
}
// UnimplementedRpcServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedRpcServer struct{}
func (UnimplementedRpcServer) Ping(context.Context, *Request) (*Response, error) {
return nil, status.Error(codes.Unimplemented, "method Ping not implemented")
}
func (UnimplementedRpcServer) mustEmbedUnimplementedRpcServer() {}
func (UnimplementedRpcServer) testEmbeddedByValue() {}
// UnsafeRpcServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to RpcServer will
// result in compilation errors.
type UnsafeRpcServer interface {
mustEmbedUnimplementedRpcServer()
}
func RegisterRpcServer(s grpc.ServiceRegistrar, srv RpcServer) {
// If the following call panics, it indicates UnimplementedRpcServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&Rpc_ServiceDesc, srv)
}
func _Rpc_Ping_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Request)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(RpcServer).Ping(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Rpc_Ping_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(RpcServer).Ping(ctx, req.(*Request))
}
return interceptor(ctx, in, info, handler)
}
// Rpc_ServiceDesc is the grpc.ServiceDesc for Rpc service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Rpc_ServiceDesc = grpc.ServiceDesc{
ServiceName: "rpc.Rpc",
HandlerType: (*RpcServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Ping",
Handler: _Rpc_Ping_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "rpc.proto",
}

38
rpc/rpcclient/rpc.go Normal file
View File

@ -0,0 +1,38 @@
// Code generated by goctl. DO NOT EDIT.
// goctl 1.9.2
// Source: rpc.proto
package rpcclient
import (
"context"
"mingyang-admin-pay/rpc/rpc"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc"
)
type (
Request = rpc.Request
Response = rpc.Response
Rpc interface {
Ping(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error)
}
defaultRpc struct {
cli zrpc.Client
}
)
func NewRpc(cli zrpc.Client) Rpc {
return &defaultRpc{
cli: cli,
}
}
func (m *defaultRpc) Ping(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error) {
client := rpc.NewRpcClient(m.cli.Conn())
return client.Ping(ctx, in, opts...)
}