encoder.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. package sdk
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. )
  8. // DefaultContentTypeV1_1 is the default content type accepted and sent by the plugins.
  9. const DefaultContentTypeV1_1 = "application/vnd.docker.plugins.v1.1+json"
  10. // DecodeRequest decodes an http request into a given structure.
  11. func DecodeRequest(w http.ResponseWriter, r *http.Request, req interface{}) (err error) {
  12. if err = json.NewDecoder(r.Body).Decode(req); err != nil {
  13. http.Error(w, err.Error(), http.StatusBadRequest)
  14. }
  15. return
  16. }
  17. // EncodeResponse encodes the given structure into an http response.
  18. func EncodeResponse(w http.ResponseWriter, res interface{}, err bool) {
  19. w.Header().Set("Content-Type", DefaultContentTypeV1_1)
  20. if err {
  21. w.WriteHeader(http.StatusInternalServerError)
  22. }
  23. json.NewEncoder(w).Encode(res)
  24. }
  25. // StreamResponse streams a response object to the client
  26. func StreamResponse(w http.ResponseWriter, data io.ReadCloser) {
  27. w.Header().Set("Content-Type", DefaultContentTypeV1_1)
  28. if _, err := copyBuf(w, data); err != nil {
  29. fmt.Printf("ERROR in stream: %v\n", err)
  30. }
  31. data.Close()
  32. }