Common isomorphic functionality in one kit.

redirect.go 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // The Isomorphic Go Project
  2. // Copyright (c) Wirecog, LLC. All rights reserved.
  3. // Use of this source code is governed by a BSD-style
  4. // license, which can be found in the LICENSE file.
  5. package isokit
  6. import (
  7. "errors"
  8. "net/http"
  9. "github.com/gopherjs/gopherjs/js"
  10. )
  11. // ServerRedirect performs a redirect when operating on the server-side.
  12. func ServerRedirect(w http.ResponseWriter, r *http.Request, destinationURL string) {
  13. http.Redirect(w, r, destinationURL, 302)
  14. }
  15. // ClientRedirect performs a redirect when operating on the client-side.
  16. func ClientRedirect(destinationURL string) {
  17. js := js.Global
  18. js.Get("location").Set("href", destinationURL)
  19. }
  20. type RedirectParams struct {
  21. ResponseWriter http.ResponseWriter
  22. Request *http.Request
  23. URL string
  24. }
  25. func Redirect(params *RedirectParams) error {
  26. if params.URL == "" {
  27. return errors.New("The URL must be specified!")
  28. }
  29. if OperatingEnvironment() == ServerEnvironment && (params.ResponseWriter == nil || params.Request == nil) {
  30. return errors.New("Either the response writer and/or the request is nil!")
  31. }
  32. switch OperatingEnvironment() {
  33. case WebBrowserEnvironment:
  34. ClientRedirect(params.URL)
  35. case ServerEnvironment:
  36. ServerRedirect(params.ResponseWriter, params.Request, params.URL)
  37. }
  38. return nil
  39. }