extensions.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2017 Google Inc. All Rights Reserved.
  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 openapiextension_v1
  15. import (
  16. "fmt"
  17. "io/ioutil"
  18. "os"
  19. "github.com/golang/protobuf/proto"
  20. "github.com/golang/protobuf/ptypes"
  21. )
  22. type documentHandler func(version string, extensionName string, document string)
  23. type extensionHandler func(name string, yamlInput string) (bool, proto.Message, error)
  24. func forInputYamlFromOpenapic(handler documentHandler) {
  25. data, err := ioutil.ReadAll(os.Stdin)
  26. if err != nil {
  27. fmt.Println("File error:", err.Error())
  28. os.Exit(1)
  29. }
  30. if len(data) == 0 {
  31. fmt.Println("No input data.")
  32. os.Exit(1)
  33. }
  34. request := &ExtensionHandlerRequest{}
  35. err = proto.Unmarshal(data, request)
  36. if err != nil {
  37. fmt.Println("Input error:", err.Error())
  38. os.Exit(1)
  39. }
  40. handler(request.Wrapper.Version, request.Wrapper.ExtensionName, request.Wrapper.Yaml)
  41. }
  42. // ProcessExtension calles the handler for a specified extension.
  43. func ProcessExtension(handleExtension extensionHandler) {
  44. response := &ExtensionHandlerResponse{}
  45. forInputYamlFromOpenapic(
  46. func(version string, extensionName string, yamlInput string) {
  47. var newObject proto.Message
  48. var err error
  49. handled, newObject, err := handleExtension(extensionName, yamlInput)
  50. if !handled {
  51. responseBytes, _ := proto.Marshal(response)
  52. os.Stdout.Write(responseBytes)
  53. os.Exit(0)
  54. }
  55. // If we reach here, then the extension is handled
  56. response.Handled = true
  57. if err != nil {
  58. response.Error = append(response.Error, err.Error())
  59. responseBytes, _ := proto.Marshal(response)
  60. os.Stdout.Write(responseBytes)
  61. os.Exit(0)
  62. }
  63. response.Value, err = ptypes.MarshalAny(newObject)
  64. if err != nil {
  65. response.Error = append(response.Error, err.Error())
  66. responseBytes, _ := proto.Marshal(response)
  67. os.Stdout.Write(responseBytes)
  68. os.Exit(0)
  69. }
  70. })
  71. responseBytes, _ := proto.Marshal(response)
  72. os.Stdout.Write(responseBytes)
  73. }