Common isomorphic functionality in one kit.

redirect.go 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. "net/http"
  8. "github.com/gopherjs/gopherjs/js"
  9. )
  10. // ServerRedirect performs a redirect when operating on the server-side.
  11. func ServerRedirect(w http.ResponseWriter, r *http.Request, destinationURL string) {
  12. http.Redirect(w, r, destinationURL, 302)
  13. }
  14. // ClientRedirect performs a redirect when operating on the client-side.
  15. func ClientRedirect(destinationURL string) {
  16. js := js.Global
  17. js.Get("location").Set("href", destinationURL)
  18. }
  19. // Redirect performs a redirect operation based on the environment that
  20. // the program is operating under.
  21. func Redirect(items ...interface{}) {
  22. var url string
  23. var w http.ResponseWriter
  24. var r *http.Request
  25. if OperatingEnvironment() == ServerEnvironment && len(items) != 3 {
  26. return
  27. }
  28. if OperatingEnvironment() == WebBrowserEnvironment && len(items) != 1 {
  29. return
  30. }
  31. for _, item := range items {
  32. switch t := item.(type) {
  33. case http.ResponseWriter:
  34. w = t
  35. case *http.Request:
  36. r = t
  37. case string:
  38. url = t
  39. }
  40. }
  41. if OperatingEnvironment() == ServerEnvironment && (w == nil || r == nil) {
  42. return
  43. }
  44. if url == "" {
  45. return
  46. }
  47. switch OperatingEnvironment() {
  48. case WebBrowserEnvironment:
  49. ClientRedirect(url)
  50. case ServerEnvironment:
  51. ServerRedirect(w, r, url)
  52. }
  53. }