Common isomorphic functionality in one kit.

redirect.go 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. // +build !clientonly
  6. package isokit
  7. import (
  8. "errors"
  9. "net/http"
  10. "github.com/gopherjs/gopherjs/js"
  11. )
  12. // ServerRedirect performs a redirect when operating on the server-side.
  13. func ServerRedirect(w http.ResponseWriter, r *http.Request, destinationURL string) {
  14. http.Redirect(w, r, destinationURL, 302)
  15. }
  16. // ClientRedirect performs a redirect when operating on the client-side.
  17. func ClientRedirect(destinationURL string) {
  18. js := js.Global
  19. js.Get("location").Set("href", destinationURL)
  20. }
  21. type RedirectParams struct {
  22. ResponseWriter http.ResponseWriter
  23. Request *http.Request
  24. URL string
  25. }
  26. func Redirect(params *RedirectParams) error {
  27. if params.URL == "" {
  28. return errors.New("The URL must be specified!")
  29. }
  30. if OperatingEnvironment() == ServerEnvironment && (params.ResponseWriter == nil || params.Request == nil) {
  31. return errors.New("Either the response writer and/or the request is nil!")
  32. }
  33. switch OperatingEnvironment() {
  34. case WebBrowserEnvironment:
  35. ClientRedirect(params.URL)
  36. case ServerEnvironment:
  37. ServerRedirect(params.ResponseWriter, params.Request, params.URL)
  38. }
  39. return nil
  40. }