options.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package rest
  2. import (
  3. "git.nspix.com/golang/micro/gateway/http"
  4. "gorm.io/gorm"
  5. "strings"
  6. )
  7. type Options struct {
  8. EnableNamespace bool
  9. Namespace string
  10. DB *gorm.DB
  11. Prefix string
  12. TablePrefixes []string
  13. RemoveTablePrefix bool
  14. Formatter *Formatter
  15. Middleware []http.Middleware
  16. MigrateOptions *MigrateOptions
  17. }
  18. type Option func(o *Options)
  19. func WithMigration(ops ...MigrateOption) Option {
  20. return func(o *Options) {
  21. if o.MigrateOptions == nil {
  22. o.MigrateOptions = &MigrateOptions{}
  23. }
  24. for _, f := range ops {
  25. f(o.MigrateOptions)
  26. }
  27. }
  28. }
  29. func WithPrefix(prefix string) Option {
  30. return func(o *Options) {
  31. if !strings.HasPrefix(prefix, "/") {
  32. prefix = "/" + prefix
  33. }
  34. if strings.HasSuffix(prefix, "/") {
  35. prefix = strings.TrimSuffix(prefix, "/")
  36. }
  37. o.Prefix = prefix
  38. }
  39. }
  40. func WithNamespace(namespace string) Option {
  41. return func(o *Options) {
  42. o.Namespace = namespace
  43. }
  44. }
  45. func WithDB(db *gorm.DB) Option {
  46. return func(o *Options) {
  47. o.DB = db
  48. }
  49. }
  50. func NewOptions() *Options {
  51. return &Options{
  52. Namespace: DefaultNamespace,
  53. Formatter: DefaultFormatter,
  54. Middleware: make([]http.Middleware, 0),
  55. MigrateOptions: &MigrateOptions{},
  56. }
  57. }