github.com/jxgolibs/go-oauth2-server@v1.0.1/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  	json.NewEncoder(w).Encode(v)
    16  }
    17  
    18  // NoContent writes a 204 no content response
    19  func NoContent(w http.ResponseWriter) {
    20  	w.WriteHeader(http.StatusNoContent)
    21  }
    22  
    23  // Error produces a JSON error response with the following structure:
    24  // {"error":"some error message"}
    25  func Error(w http.ResponseWriter, err string, code int) {
    26  	w.Header().Set("Content-Type", "application/json; charset=utf-8")
    27  	w.WriteHeader(code)
    28  	json.NewEncoder(w).Encode(map[string]string{"error": err})
    29  }
    30  
    31  // UnauthorizedError has to contain WWW-Authenticate header
    32  // See http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html#rfc.section.3
    33  func UnauthorizedError(w http.ResponseWriter, err string) {
    34  	// TODO - include error if the request contained an access token
    35  	w.Header().Set("WWW-Authenticate", fmt.Sprintf("Bearer realm=%s", realm))
    36  	Error(w, err, http.StatusUnauthorized)
    37  }