github.com/msales/pkg/v3@v3.24.0/httpx/json.go (about)

     1  package httpx
     2  
     3  import (
     4  	"encoding/json"
     5  	"net/http"
     6  )
     7  
     8  const (
     9  	// JSONContentType represents MIME type for JSON content.
    10  	JSONContentType = "application/json"
    11  )
    12  
    13  // WriteJSONResponse encodes json content to the ResponseWriter.
    14  func WriteJSONResponse(w http.ResponseWriter, code int, v interface{}) error {
    15  	raw, err := json.Marshal(v)
    16  	if err != nil {
    17  		w.WriteHeader(http.StatusInternalServerError)
    18  		return err
    19  	}
    20  
    21  	w.Header().Set("Content-Type", JSONContentType)
    22  	w.WriteHeader(code)
    23  
    24  	if _, err = w.Write(raw); err != nil {
    25  		return err
    26  	}
    27  
    28  	return nil
    29  }