1
0

visitor_plugin.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2025 The frp Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package v1
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "reflect"
  21. )
  22. const (
  23. VisitorPluginVirtualNet = "virtual_net"
  24. )
  25. var visitorPluginOptionsTypeMap = map[string]reflect.Type{
  26. VisitorPluginVirtualNet: reflect.TypeOf(VirtualNetVisitorPluginOptions{}),
  27. }
  28. type VisitorPluginOptions interface {
  29. Complete()
  30. }
  31. type TypedVisitorPluginOptions struct {
  32. Type string `json:"type"`
  33. VisitorPluginOptions
  34. }
  35. func (c *TypedVisitorPluginOptions) UnmarshalJSON(b []byte) error {
  36. if len(b) == 4 && string(b) == "null" {
  37. return nil
  38. }
  39. typeStruct := struct {
  40. Type string `json:"type"`
  41. }{}
  42. if err := json.Unmarshal(b, &typeStruct); err != nil {
  43. return err
  44. }
  45. c.Type = typeStruct.Type
  46. if c.Type == "" {
  47. return errors.New("visitor plugin type is empty")
  48. }
  49. v, ok := visitorPluginOptionsTypeMap[typeStruct.Type]
  50. if !ok {
  51. return fmt.Errorf("unknown visitor plugin type: %s", typeStruct.Type)
  52. }
  53. options := reflect.New(v).Interface().(VisitorPluginOptions)
  54. decoder := json.NewDecoder(bytes.NewBuffer(b))
  55. if DisallowUnknownFields {
  56. decoder.DisallowUnknownFields()
  57. }
  58. if err := decoder.Decode(options); err != nil {
  59. return fmt.Errorf("unmarshal VisitorPluginOptions error: %v", err)
  60. }
  61. c.VisitorPluginOptions = options
  62. return nil
  63. }
  64. func (c *TypedVisitorPluginOptions) MarshalJSON() ([]byte, error) {
  65. return json.Marshal(c.VisitorPluginOptions)
  66. }
  67. type VirtualNetVisitorPluginOptions struct {
  68. Type string `json:"type"`
  69. DestinationIP string `json:"destinationIP"`
  70. }
  71. func (o *VirtualNetVisitorPluginOptions) Complete() {}