odin-doc

Odin Develop Document

View project on GitHub

开发步骤三


具体业务逻辑开发代码需自由发挥

odin提供两种子服务模板,分别是:

简单直接的服务(HelloService)

业务逻辑简单可直接在ServiceImpl中实现业务逻辑

package serviceImpl

import (
    "context"
    "fmt"

    "odin/proto"
)

type HelloService struct {
}

func NewHelloService() *HelloService {
    return new(HelloService)
}

func (this *HelloService) SayHello(ctx context.Context, req *proto.SayHelloRequest, resp *proto.SayHelloResponse) error {
    reply := fmt.Sprintf("i'm hello service,recv greeting:%s", req.Greeting)
    resp.Reply = reply
    return nil
}

DDD设计原则的实体服务UserService

serviceImpl层负责参数拼装,调用不同实体方法,组合实体实现业务逻辑。实体层提供实体接口,实现实体内部逻辑

package serviceImpl

import (
    "context"
    "odin/app/entity"
    "odin/app/repository"

    "odin/proto"
)

type UserService struct {
}

func NewUserService() *UserService {
    return new(UserService)
}

func (this *UserService) UserInfo(ctx context.Context, req *proto.UserInfoRequest, resp *proto.UserInfoResponse) error {
    userRepo, err := repository.GetUserRepo(ctx)
    if err != nil {
        return err
    }
    user, err := userRepo.GetUserInfo(ctx, req.Id)
    if err != nil {
        return err
    }
    resp.Name = user.Name
    resp.Age = user.Age
    resp.City = user.City
    return nil
}

func (this *UserService) AddUser(ctx context.Context, req *proto.AddUserRequest, resp *proto.AddUserResponse) error {
    userRepo, err := repository.GetUserRepo(ctx)
    if err != nil {
        return err
    }
    user := &entity.User{
        Name: req.Name,
        Age:  req.Age,
        City: req.City,
    }
    id, err := userRepo.AddUser(ctx, user)
    if err != nil {
        return err
    }
    resp.Id = id
    return nil
}

func (this *UserService) UpdateUser(ctx context.Context, req *proto.UpdateUserRequest, resp *proto.UpdateUserResponse) error {
    userRepo, err := repository.GetUserRepo(ctx)
    if err != nil {
        return err
    }
    user := &entity.User{
        Id:   req.Id,
        Name: req.Name,
        Age:  req.Age,
        City: req.City,
    }
    err = userRepo.UpdateUser(ctx, user)
    if err != nil {
        return err
    }
    return nil
}