github.com/decred/politeia@v1.4.0/util/json.go (about)

     1  // Copyright (c) 2017-2021 The Decred developers
     2  // Use of this source code is governed by an ISC
     3  // license that can be found in the LICENSE file.
     4  
     5  package util
     6  
     7  import (
     8  	"encoding/json"
     9  	"fmt"
    10  	"io"
    11  	"net/http"
    12  )
    13  
    14  func RespondWithError(w http.ResponseWriter, code int, message string) {
    15  	RespondWithJSON(w, code, map[string]string{"error": message})
    16  }
    17  
    18  func RespondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
    19  	response, _ := json.Marshal(payload)
    20  
    21  	w.Header().Set("Strict-Transport-Security",
    22  		"max-age=63072000; includeSubDomains")
    23  	w.Header().Set("X-Content-Type-Options", "nosniff")
    24  	w.Header().Set("Referrer-Policy", "same-origin")
    25  	w.Header().Set("X-Frame-Options", "DENY")
    26  	w.Header().Set("X-XSS-Protection", "1; mode=block")
    27  	w.Header().Set("Content-Type", "application/json; charset=utf-8")
    28  
    29  	w.WriteHeader(code)
    30  	w.Write(response)
    31  }
    32  
    33  func RespondRaw(w http.ResponseWriter, code int, payload []byte) {
    34  	w.Header().Set("Strict-Transport-Security",
    35  		"max-age=63072000; includeSubDomains")
    36  	w.Header().Set("X-Content-Type-Options", "nosniff")
    37  	w.Header().Set("Referrer-Policy", "same-origin")
    38  	w.Header().Set("X-Frame-Options", "DENY")
    39  	w.Header().Set("X-XSS-Protection", "1; mode=block")
    40  	w.Header().Set("Content-Type", "application/json; charset=utf-8")
    41  
    42  	w.WriteHeader(code)
    43  	w.Write(payload)
    44  }
    45  
    46  // GetErrorFromJSON returns the error that is embedded in a JSON reply.
    47  func GetErrorFromJSON(r io.Reader) (interface{}, error) {
    48  	var e interface{}
    49  	decoder := json.NewDecoder(r)
    50  	if err := decoder.Decode(&e); err != nil {
    51  		return nil, err
    52  	}
    53  	return e, nil
    54  }
    55  
    56  // FormatJSON returns a pretty printed JSON string for the provided structure.
    57  func FormatJSON(v interface{}) string {
    58  	b, err := json.MarshalIndent(v, "", "  ")
    59  	if err != nil {
    60  		return fmt.Sprintf("MarshalIndent: %v", err)
    61  	}
    62  	return string(b)
    63  }