本文是区块链浏览器系列的第五篇,项目完整代码在这里。

在上一篇文章中给浏览器增加了简单的用户认证,至此浏览器的基本功能就已经大致完成了。

在这片文章中,我将使用kratos对区块链浏览器器进行重构,使之同时支持http和gRPC。

1. 项目结构

项目结构如下:

$ tree.├── api                                     │ └── browser│     └── v1│         ├── block_grpc.pb.go│         ├── block_http.pb.go│         ├── block.pb.go│         ├── block.proto│         ├── browser_grpc.pb.go│         ├── browser_http.pb.go│         ├── browser.pb.go│         └── browser.proto├── cmd│ └── example│     ├── main.go│     ├── wire_gen.go│     └── wire.go├── configs│ └── config.yaml├── Dockerfile├── go.mod├── go.sum├── internal│ ├── biz│ │ ├── account.go│ │ ├── biz.go│ │ ├── README.md│ │ └── repo.go│ ├── conf│ │ ├── conf.pb.go│ │ └── conf.proto│ ├── data│ │ ├── account.go│ │ ├── data.go│ │ └── README.md│ ├── db│ │ ├── db.go│ │ ├── mysql│ │ │ └── mysql.go│ │ ├── pg│ │ │ └── pg.go│ │ └── sqlite3│ │     └── sqlite3.go│ ├── server│ │ ├── grpc.go│ │ ├── http.go│ │ └── server.go│ ├── service│ │ ├── block.go│ │ ├── browser.go│ │ ├── global.go│ │ ├── README.md│ │ ├── service.go│ │ └── utils.go│ └── utils│     ├── putils.go│     └── utils.go├── LICENSE├── Makefile├── openapi.yaml├── README.md└── third_party    ├── errors    │ └── errors.proto    ├── google    │ ├── api    │ │ ├── annotations.proto    │ │ ├── client.proto    │ │ ├── field_behavior.proto    │ │ ├── httpbody.proto    │ │ └── http.proto    │ └── protobuf    │     ├── any.proto    │     ├── api.proto    │     ├── compiler    │     │ └── plugin.proto    │     ├── descriptor.proto    │     ├── duration.proto    │     ├── empty.proto    │     ├── field_mask.proto    │     ├── source_context.proto    │     ├── struct.proto    │     ├── timestamp.proto    │     ├── type.proto    │     └── wrappers.proto    ├── openapi    │ └── v3    │     ├── annotations.proto    │     └── openapi.proto    ├── README.md    └── validate        ├── README.md        └── validate.proto26 directories, 66 files
  • api 定义接口
    • block.prot:区块上传和区块解析的接口
    • browser:用户认证相关接口,包括用户注册、用户登录以及刷新token
  • cmd:本地调试使用,基于wire实现
  • configs:存放项目的配置文件
  • internal:业务逻辑实现
    • biz:类似DTO,封装数据库操作
    • conf:定义项目配置项
    • data:数据处理,目前主要是处理用户认证相关数据
    • db:数据库操作实现
    • server:注册http和gRPC服务
    • service:实现浏览器业务逻辑
    • utils:工具类
  • third_party:依赖的第三方库,主要是protobuf相关的第三方库

2. api接口定义

block.proto中定义区块上传和解析操作:

syntax = "proto3";package api.browser.v1;option go_package = "mengbin92/browser/api/browser/v1;v1";import "google/api/annotations.proto";service Block {  rpc UpChaincode(UploadRequest) returns (UploadResponse) {    option (google.api.http) = {      post : "/v1/block/up"      body : "*"    };  };  rpc ParseBlock(ParseRequest) returns (ParseResponse) {    option (google.api.http) = {      get : "/v1/block/parse"    };  }}message UploadRequest {  string name = 1;  bytes content = 2;}message UploadResponse {  bool result = 1;  string name = 2;}message ParseRequest {  enum BlockOperation {    BLOCK = 0;    HEADER = 1;    DATA = 2;    CONFIG = 3;    CHAINCODE = 4;    ACTIONS = 5;    TRANSACTION = 6;    INPUT = 7;    RWSET = 8;    CHANNEL = 9;    ENDORSEMENTS = 10;    CREATOR = 11;    METADATA = 12;  }  string name = 1;  BlockOperation operation = 2;}message ParseResponse { bytes data = 1; }message Endorser {  string MSP = 1;  string Name = 2;}message Endorsers { repeated Endorser endorsers = 1; }

browser.proto定义用户注册、登录和token刷新操作:

syntax = "proto3";package api.browser.v1;option go_package = "mengbin92/browser/api/browser/v1;v1";import "google/protobuf/timestamp.proto";import "google/api/annotations.proto";service Browser {  rpc GetToken(Login) returns (LoginResponse) {    option (google.api.http) = {      post : "/v1/user/login"      body : "*"    };  };  rpc Regisger(Login) returns (LoginResponse) {    option (google.api.http) = {      post : "/v1/user/register"      body : "*"    };  };  rpc RefreshToken(RefreshRequest) returns (LoginResponse) {    option (google.api.http) = {      get : "/v1/user/refresh/{id}"    };  };}message User {  uint64 id = 1;  string name = 2;  string password = 3;  string salt = 4;  google.protobuf.Timestamp create_at = 5;  google.protobuf.Timestamp update_at = 6;  google.protobuf.Timestamp delete_at = 7;}message LoginResponse {  string token = 1;  int64 expire = 2;  uint64 id = 3;  string username = 4;}message Login {  string username = 1;  string password = 2;}message RefreshRequest { uint64 id = 1; }

在项目根目录下执行下面命令即可完成框架生成:

# 生成对应的go文件$ make api# 生成service文件$ kratos proto server api/browser/v1/block.proto -t internal/service$ kratos proto server api/browser/v1/browser.proto -t internal/service

3. biz介绍

biz定义了用户认证相关的接口,供service调用,接口内容如下:

type AccountRepo interface {    // 用户注册Register(context.Context, string, string) (*v1.LoginResponse, error)    // 用户登录,用于获取tokenLogin(context.Context, string, string) (*v1.LoginResponse, error)    // 刷新tokenRefreshToken(context.Context, uint64) (*v1.LoginResponse, error)}

4. conf介绍

conf定义项目的配置项,也是通过protobuf定义的:

syntax = "proto3";package browser.api;option go_package = "mengbin92/browser/internal/conf;conf";import "google/protobuf/duration.proto";message Bootstrap {  Server server = 1;  Log log = 2;  Data data = 3;}message Server {  message HTTP {    string network = 1;    string addr = 2;    google.protobuf.Duration timeout = 3;  }  message GRPC {    string network = 1;    string addr = 2;    google.protobuf.Duration timeout = 3;  }  enum AuthType{    TOKENAUTH = 0;    BASICAUTH = 1;    NOAUTH = 2;  }  HTTP http = 1;  GRPC grpc = 2;  TLS tls = 3;  // 2: no auth; 1: basic auth; default: 0, token auth  AuthType auth_type = 4;  Auth auth = 5;}message TLS {  // 是否启用tls  bool enbale = 1;  // 证书路径  string cert = 2;  // 对应私钥路径  string key = 3;}message Log {  // 日志级别设置  // 支持debug(-1)、info(0)、warn(1)、error(2)、dpanic(3)、panic(4)、fatal(5)  int32 level = 1;  // 日志输出格式,支持json or console  string format = 2;}message Database {  // 数据库类型:mysql、sqlite3、postgres  string driver = 1;  string source = 2;  // 最大空闲连接数  int64 max_idle_conn = 3;  // 最大连接数  int64 max_open_conn = 4;  // 连接空闲超时参数  google.protobuf.Duration conn_max_lifetime = 5;}message Redis {  string network = 1;  string addr = 2;  string password = 3;  int32 db = 4;  google.protobuf.Duration dial_timeout = 5;  google.protobuf.Duration read_timeout = 6;  google.protobuf.Duration write_timeout = 7;}message Data {  Database database = 1;  Redis redis = 2;}message Auth {  // jwt 秘钥,暂未启用  string jwt_secret = 1;  // token过期时间  google.protobuf.Duration expire = 2;}

5. data介绍

data中定义了AccountRepo结构,主要实现了biz中与数据库交互的业务逻辑:

type AccountRepo struct {data      *Datalog       *log.HelperjwtSecret stringexpire    time.Duration}func NewAccountRepo(data *Data, logger log.Logger, auth *conf.Auth) biz.AccountRepo {return &AccountRepo{data:      data,log:       log.NewHelper(logger),jwtSecret: auth.JwtSecret,expire:    auth.Expire.AsDuration(),}}func genSalt() string {uid, _ := uuid.NewRandom()return uid.String()}func (ar *AccountRepo) Register(ctx context.Context, username, password string) (*v1.LoginResponse, error) {salt := genSalt()u := &User{Name:     username,Password: utils.CalcPassword(password, salt),Salt:     salt,}if err := ar.data.db.Save(u).Error; err != nil {ar.log.Errorf("save user data error: %s", err.Error())return nil, errors.Wrap(err, "save user error")}now := time.Now()tokenString, err := ar.genToken(uint64(u.ID), now)if err != nil {ar.log.Errorf("create token error: %s", err.Error())return nil, errors.Wrap(err, "create token error")}return &v1.LoginResponse{Token:    tokenString,Expire:   now.Add(ar.expire).Unix(),Id:       uint64(u.ID),Username: u.Name,}, nil}func (ar *AccountRepo) Login(ctx context.Context, username, password string) (*v1.LoginResponse, error) {user, err := ar.getUserByName(ctx, username)if err != nil {ar.log.Errorf("get user from data error: %s", err.Error())return nil, errors.Wrap(err, "GetUserByName error")}if utils.CalcPassword(password, user.Salt) != user.Password {ar.log.Error("user name or password is incorrect")return nil, errors.New("user name or password is incorrect")}now := time.Now()tokenString, err := ar.genToken(user.Id, now)if err != nil {ar.log.Errorf("create token error: %s", err.Error())return nil, errors.Wrap(err, "create token error")}return &v1.LoginResponse{Token:    tokenString,Expire:   now.Add(ar.expire).Unix(),Id:       user.Id,Username: user.Name,}, nil}func (ar *AccountRepo) RefreshToken(ctx context.Context, id uint64) (*v1.LoginResponse, error) {user, err := ar.getUserById(ctx, id)if err != nil {ar.log.Errorf("get user from data error: %s", err.Error())return nil, errors.Wrap(err, "GetUserByName error")}now := time.Now()tokenString, err := ar.genToken(user.Id, now)if err != nil {ar.log.Errorf("create token error: %s", err.Error())return nil, errors.Wrap(err, "create token error")}return &v1.LoginResponse{Token:    tokenString,Expire:   now.Add(ar.expire).Unix(),Id:       user.Id,Username: user.Name,}, nil}

6. service介绍

service主要实现api中定义的接口:

  • block.go

    type BlockService struct {pb.UnimplementedBlockServer}func NewBlockService() *BlockService {return &BlockService{}}func (s *BlockService) UpChaincode(ctx context.Context, req *pb.UploadRequest) (*pb.UploadResponse, error) {    // 与gin实现版本类似,客户端上传区块数据存储到服务端return &pb.UploadResponse{Result: true,Name:   req.Name,}, nil}func (s *BlockService) ParseBlock(ctx context.Context, req *pb.ParseRequest) (*pb.ParseResponse, error) {    // 与gin实现版本逻辑类似,这里就不再赘述了return &pb.ParseResponse{}, nil}
  • browser.go

    type BrowserService struct {account *biz.AccountUsecasepb.UnimplementedBrowserServer}func NewBrowserService(repo *biz.AccountUsecase, logger klog.Logger) *BrowserService {log = klog.NewHelper(logger)return &BrowserService{account: repo,}}func (s *BrowserService) GetToken(ctx context.Context, req *pb.Login) (*pb.LoginResponse, error) {return s.account.Login(ctx, req.Username, req.Password)}func (s *BrowserService) Regisger(ctx context.Context, req *pb.Login) (*pb.LoginResponse, error) {return s.account.Register(ctx, req.Username, req.Password)}func (s *BrowserService) RefreshToken(ctx context.Context, req *pb.RefreshRequest) (*pb.LoginResponse, error) {return s.account.RefreshToken(ctx, req.Id)}

声明:本作品采用署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)进行许可,使用时请注明出处。
Author: mengbin
blog: mengbin
Github: mengbin92
cnblogs: 恋水无意