compute_tax_function.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package provider
  2. import (
  3. "context"
  4. "math"
  5. "github.com/hashicorp/terraform-plugin-framework/function"
  6. )
  7. var (
  8. _ function.Function = &ComputeTaxFunction{}
  9. )
  10. type ComputeTaxFunction struct{}
  11. func NewComputeTaxFunction() function.Function {
  12. return &ComputeTaxFunction{}
  13. }
  14. func (f *ComputeTaxFunction) Metadata(ctx context.Context, req function.MetadataRequest, resp *function.MetadataResponse) {
  15. resp.Name = "compute_tax"
  16. }
  17. func (f *ComputeTaxFunction) Definition(ctx context.Context, req function.DefinitionRequest, resp *function.DefinitionResponse) {
  18. resp.Definition = function.Definition{
  19. Parameters: []function.Parameter{
  20. function.Float64Parameter{
  21. Description: "Price of coffee item.",
  22. Name: "price",
  23. },
  24. function.Float64Parameter{
  25. Description: "Tax rate. 0.085 == 8.5%",
  26. Name: "rate",
  27. },
  28. },
  29. Return: function.Float64Return{},
  30. Summary: "Compute tax for coffee",
  31. Description: "Given a price and tax rate, return the total cost including tax.",
  32. }
  33. }
  34. func (f *ComputeTaxFunction) Run(ctx context.Context, req function.RunRequest, resp *function.RunResponse) {
  35. var (
  36. price, rate, total float64
  37. )
  38. // 1. Read Terraform argument data into the variables.
  39. resp.Error = function.ConcatFuncErrors(
  40. resp.Error,
  41. req.Arguments.Get(ctx, &price, &rate),
  42. )
  43. // 2. Perform the calculation
  44. total = math.Round((price+price*rate)*100) / 100
  45. // 3. Set the result on the state
  46. resp.Error = function.ConcatFuncErrors(
  47. resp.Error,
  48. resp.Result.Set(ctx, total),
  49. )
  50. }