github.com/machinebox/remoto@v0.1.2-0.20191024144331-eff21a7d321f/go/remotohttp/encode.go (about)

     1  package remotohttp
     2  
     3  import (
     4  	"compress/gzip"
     5  	"encoding/json"
     6  	"io"
     7  	"net/http"
     8  	"strings"
     9  
    10  	"github.com/pkg/errors"
    11  )
    12  
    13  // Encode writes the response.
    14  func Encode(w http.ResponseWriter, r *http.Request, status int, v interface{}) error {
    15  	b, err := json.Marshal(v)
    16  	if err != nil {
    17  		return errors.Wrap(err, "encode json")
    18  	}
    19  	var out io.Writer = w
    20  	if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
    21  		w.Header().Set("Content-Encoding", "gzip")
    22  		gzw := gzip.NewWriter(w)
    23  		out = gzw
    24  		defer gzw.Close()
    25  	}
    26  	w.Header().Set("Content-Type", "application/json; chatset=utf-8")
    27  	w.WriteHeader(status)
    28  	if _, err := out.Write(b); err != nil {
    29  		return err
    30  	}
    31  	return nil
    32  }
    33  
    34  // EncodeErr writes an error response with http.StatusInternalServerError.
    35  func EncodeErr(w http.ResponseWriter, r *http.Request, err error) error {
    36  	// returns [{"error":"message"}]
    37  	e := []struct {
    38  		Error string `json:"error"`
    39  	}{
    40  		{
    41  			Error: err.Error(),
    42  		},
    43  	}
    44  	return Encode(w, r, http.StatusInternalServerError, e)
    45  }