extensions.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2017 Google LLC. 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 gnostic_extension_v1
  15. import (
  16. "io/ioutil"
  17. "log"
  18. "os"
  19. "github.com/golang/protobuf/proto"
  20. "github.com/golang/protobuf/ptypes"
  21. )
  22. type extensionHandler func(name string, yamlInput string) (bool, proto.Message, error)
  23. // Main implements the main program of an extension handler.
  24. func Main(handler extensionHandler) {
  25. // unpack the request
  26. data, err := ioutil.ReadAll(os.Stdin)
  27. if err != nil {
  28. log.Println("File error:", err.Error())
  29. os.Exit(1)
  30. }
  31. if len(data) == 0 {
  32. log.Println("No input data.")
  33. os.Exit(1)
  34. }
  35. request := &ExtensionHandlerRequest{}
  36. err = proto.Unmarshal(data, request)
  37. if err != nil {
  38. log.Println("Input error:", err.Error())
  39. os.Exit(1)
  40. }
  41. // call the handler
  42. handled, output, err := handler(request.Wrapper.ExtensionName, request.Wrapper.Yaml)
  43. // respond with the output of the handler
  44. response := &ExtensionHandlerResponse{
  45. Handled: false, // default assumption
  46. Errors: make([]string, 0),
  47. }
  48. if err != nil {
  49. response.Errors = append(response.Errors, err.Error())
  50. } else if handled {
  51. response.Handled = true
  52. response.Value, err = ptypes.MarshalAny(output)
  53. if err != nil {
  54. response.Errors = append(response.Errors, err.Error())
  55. }
  56. }
  57. responseBytes, _ := proto.Marshal(response)
  58. os.Stdout.Write(responseBytes)
  59. }