shortenlogic.go 824 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package logic
  2. import (
  3. "context"
  4. "shorturl/rpc/transform/internal/svc"
  5. "shorturl/rpc/transform/model"
  6. transform "shorturl/rpc/transform/pb"
  7. "github.com/tal-tech/go-zero/core/hash"
  8. "github.com/tal-tech/go-zero/core/logx"
  9. )
  10. type ShortenLogic struct {
  11. logx.Logger
  12. ctx context.Context
  13. svcCtx *svc.ServiceContext
  14. }
  15. func NewShortenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShortenLogic {
  16. return &ShortenLogic{
  17. Logger: logx.WithContext(ctx),
  18. ctx: ctx,
  19. svcCtx: svcCtx,
  20. }
  21. }
  22. func (l *ShortenLogic) Shorten(in *transform.ShortenReq) (*transform.ShortenResp, error) {
  23. key := hash.Md5Hex([]byte(in.Url))[:6]
  24. _, err := l.svcCtx.Model.Insert(model.Shorturl{
  25. Shorten: key,
  26. Url: in.Url,
  27. })
  28. if err != nil {
  29. return nil, err
  30. }
  31. return &transform.ShortenResp{
  32. Shorten: key,
  33. }, nil
  34. }