container.go 856 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package translation
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. )
  7. // Container contains a source string and a map of arguments.
  8. type Container struct {
  9. Message string `json:"message"`
  10. Args map[string]any `json:"args,omitempty"`
  11. }
  12. // C creates a new Container.
  13. func C(message string, args ...map[string]any) *Container {
  14. if len(args) == 0 {
  15. return &Container{
  16. Message: message,
  17. }
  18. }
  19. return &Container{
  20. Message: message,
  21. Args: args[0],
  22. }
  23. }
  24. // ToString returns the source string with the arguments replaced.
  25. func (c *Container) ToString() (result string) {
  26. result = c.Message
  27. for k, v := range c.Args {
  28. result = strings.ReplaceAll(result, "%{"+k+"}", fmt.Sprintf("%v", v))
  29. }
  30. return
  31. }
  32. // ToJSON returns the arguments as a JSON object.
  33. func (c *Container) ToJSON() (result []byte, err error) {
  34. return json.Marshal(c)
  35. }