github.com/jxgolibs/go-oauth2-server@v1.0.1/web/util.go (about)

     1  package web
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"net/url"
     7  )
     8  
     9  // Redirects to a new path while keeping current request's query string
    10  func redirectWithQueryString(to string, query url.Values, w http.ResponseWriter, r *http.Request) {
    11  	http.Redirect(w, r, fmt.Sprintf("%s%s", to, getQueryString(query)), http.StatusFound)
    12  }
    13  
    14  // Redirects to a new path with the query string moved to the URL fragment
    15  func redirectWithFragment(to string, query url.Values, w http.ResponseWriter, r *http.Request) {
    16  	http.Redirect(w, r, fmt.Sprintf("%s#%s", to, query.Encode()), http.StatusFound)
    17  }
    18  
    19  // Returns string encoded query string of the request
    20  func getQueryString(query url.Values) string {
    21  	encoded := query.Encode()
    22  	if len(encoded) > 0 {
    23  		encoded = fmt.Sprintf("?%s", encoded)
    24  	}
    25  	return encoded
    26  }
    27  
    28  // Helper function to handle redirecting failed or declined authorization
    29  func errorRedirect(w http.ResponseWriter, r *http.Request, redirectURI *url.URL, err, state, responseType string) {
    30  	query := redirectURI.Query()
    31  	query.Set("error", err)
    32  	if state != "" {
    33  		query.Set("state", state)
    34  	}
    35  	if responseType == "code" {
    36  		redirectWithQueryString(redirectURI.String(), query, w, r)
    37  	}
    38  	if responseType == "token" {
    39  		redirectWithFragment(redirectURI.String(), query, w, r)
    40  	}
    41  }