github.com/gocaveman/caveman@v0.0.0-20191211162744-0ddf99dbdf6e/webutil/json.go (about)

     1  package webutil
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"mime"
     7  	"net/http"
     8  )
     9  
    10  var ErrNotJSONContent = errors.New("cannot parse, not json content")
    11  
    12  // ParseJSON parses a request with content-type application/json into the struct you provide.
    13  // Uses json.Decoder.
    14  func ParseJSON(r *http.Request, v interface{}) error {
    15  
    16  	ct, _, _ := mime.ParseMediaType(r.Header.Get("content-type"))
    17  	if ct != "application/json" {
    18  		return ErrNotJSONContent
    19  	}
    20  
    21  	dec := json.NewDecoder(r.Body)
    22  	err := dec.Decode(v)
    23  	if err != nil {
    24  		return err
    25  	}
    26  
    27  	return nil
    28  }
    29  
    30  // WriteJSON writes a response as content-type application/json.
    31  // Uses json.Encoder.
    32  func WriteJSON(w http.ResponseWriter, v interface{}, status int) error {
    33  
    34  	w.Header().Set("content-type", "application/json")
    35  
    36  	w.WriteHeader(status)
    37  
    38  	enc := json.NewEncoder(w)
    39  	err := enc.Encode(v)
    40  	if err != nil {
    41  		return err
    42  	}
    43  
    44  	return nil
    45  }