feat: bootstrap reusable GoOmni framework

This commit is contained in:
2026-09-20 22:06:24 +08:00
commit 8b19aa79ee
60 changed files with 4923 additions and 0 deletions

View File

@@ -0,0 +1,71 @@
package service
import (
"context"
"net/mail"
"strings"
"unicode/utf8"
"git.yuntuo.hk/k2safe/go-omni/examples/reference/model"
)
// UserRepository describes the storage operations the business needs.
// Implementations must atomically enforce unique, normalized email addresses.
type UserRepository interface {
Create(context.Context, model.UserInput) (model.User, error)
Get(context.Context, int64) (model.User, error)
List(context.Context, int, int) (model.UserPage, error)
Update(context.Context, int64, model.UserInput) (model.User, error)
Delete(context.Context, int64) error
}
type Users struct {
repository UserRepository
}
func NewUsers(repository UserRepository) *Users {
return &Users{repository: repository}
}
func (s *Users) Create(ctx context.Context, input model.UserInput) (model.User, error) {
input, err := normalize(input)
if err != nil {
return model.User{}, err
}
return s.repository.Create(ctx, input)
}
func (s *Users) Get(ctx context.Context, id int64) (model.User, error) {
return s.repository.Get(ctx, id)
}
func (s *Users) List(ctx context.Context, page, pageSize int) (model.UserPage, error) {
if page < 1 || pageSize < 1 || pageSize > 100 {
return model.UserPage{}, model.ErrInvalidPage
}
return s.repository.List(ctx, page, pageSize)
}
func (s *Users) Update(ctx context.Context, id int64, input model.UserInput) (model.User, error) {
input, err := normalize(input)
if err != nil {
return model.User{}, err
}
return s.repository.Update(ctx, id, input)
}
func (s *Users) Delete(ctx context.Context, id int64) error {
return s.repository.Delete(ctx, id)
}
func normalize(input model.UserInput) (model.UserInput, error) {
input.Name = strings.TrimSpace(input.Name)
// This example treats the entire email address as case-insensitive.
input.Email = strings.ToLower(strings.TrimSpace(input.Email))
address, err := mail.ParseAddress(input.Email)
if input.Name == "" || utf8.RuneCountInString(input.Name) > 100 ||
len(input.Email) > 254 || err != nil || address.Address != input.Email {
return model.UserInput{}, model.ErrInvalidUser
}
return input, nil
}