github.com/blend/go-sdk@v1.20220411.3/webutil/write_helpers.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package webutil
     9  
    10  import (
    11  	"encoding/json"
    12  	"encoding/xml"
    13  	"io"
    14  	"net"
    15  	"net/http"
    16  
    17  	"github.com/blend/go-sdk/ex"
    18  )
    19  
    20  // Errors
    21  const (
    22  	ErrNetWrite ex.Class = "network write error"
    23  )
    24  
    25  // WriteNoContent writes http.StatusNoContent for a request.
    26  func WriteNoContent(w http.ResponseWriter) error {
    27  	w.WriteHeader(http.StatusNoContent)
    28  	return nil
    29  }
    30  
    31  // WriteRawContent writes raw content for the request.
    32  func WriteRawContent(w http.ResponseWriter, statusCode int, content []byte) error {
    33  	w.WriteHeader(statusCode)
    34  	_, err := w.Write(content)
    35  	return ex.New(err)
    36  }
    37  
    38  // WriteJSON marshalls an object to json.
    39  func WriteJSON(w http.ResponseWriter, statusCode int, response interface{}) error {
    40  	w.Header().Set(HeaderContentType, ContentTypeApplicationJSON)
    41  	w.WriteHeader(statusCode)
    42  	if err := json.NewEncoder(w).Encode(response); err != nil {
    43  		if typed, ok := err.(*net.OpError); ok {
    44  			return ex.New(ErrNetWrite, ex.OptInner(typed))
    45  		}
    46  		return ex.New(err)
    47  	}
    48  	return nil
    49  }
    50  
    51  // WriteXML marshalls an object to json.
    52  func WriteXML(w http.ResponseWriter, statusCode int, response interface{}) error {
    53  	w.Header().Set(HeaderContentType, ContentTypeXML)
    54  	w.WriteHeader(statusCode)
    55  	if err := xml.NewEncoder(w).Encode(response); err != nil {
    56  		if typed, ok := err.(*net.OpError); ok {
    57  			return ex.New(ErrNetWrite, ex.OptInner(typed))
    58  		}
    59  		return ex.New(err)
    60  	}
    61  	return nil
    62  }
    63  
    64  // DeserializeReaderAsJSON deserializes a post body as json to a given object.
    65  func DeserializeReaderAsJSON(object interface{}, body io.ReadCloser) error {
    66  	defer body.Close()
    67  	return ex.New(json.NewDecoder(body).Decode(object))
    68  }