github.com/resonatecoop/id@v1.1.0-43/util/response/response.go (about)

     1  package response
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/http"
     7  )
     8  
     9  var realm = "go_oauth2_server"
    10  
    11  // WriteJSON writes JSON response
    12  func WriteJSON(w http.ResponseWriter, v interface{}, code int) {
    13  	w.Header().Set("Content-Type", "application/json; charset=utf-8")
    14  	w.WriteHeader(code)
    15  	err := json.NewEncoder(w).Encode(v)
    16  	if err != nil {
    17  		http.Error(w, err.Error(), http.StatusInternalServerError)
    18  		return
    19  	}
    20  }
    21  
    22  // NoContent writes a 204 no content response
    23  func NoContent(w http.ResponseWriter) {
    24  	w.WriteHeader(http.StatusNoContent)
    25  }
    26  
    27  // Error produces a JSON error response with the following structure:
    28  // {"error":"some error message"}
    29  func Error(w http.ResponseWriter, err string, code int) {
    30  	w.Header().Set("Content-Type", "application/json; charset=utf-8")
    31  	w.WriteHeader(code)
    32  	enc_err := json.NewEncoder(w).Encode(map[string]string{"error": err})
    33  	if enc_err != nil {
    34  		http.Error(w, enc_err.Error(), http.StatusInternalServerError)
    35  		return
    36  	}
    37  }
    38  
    39  // UnauthorizedError has to contain WWW-Authenticate header
    40  // See http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html#rfc.section.3
    41  func UnauthorizedError(w http.ResponseWriter, err string) {
    42  	// TODO - include error if the request contained an access token
    43  	w.Header().Set("WWW-Authenticate", fmt.Sprintf("Bearer realm=%s", realm))
    44  	Error(w, err, http.StatusUnauthorized)
    45  }