Common isomorphic functionality in one kit.

redirect.go 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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/go-humble/detect"
  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, 301)
  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. // Redirect performs a redirect operation based on the environment that
  21. // the program is operating under.
  22. func Redirect(items ...interface{}) {
  23. var url string
  24. var w http.ResponseWriter
  25. var r *http.Request
  26. if detect.IsServer() && len(items) != 3 {
  27. return
  28. }
  29. if detect.IsBrowser() && len(items) != 1 {
  30. return
  31. }
  32. for _, item := range items {
  33. switch t := item.(type) {
  34. case http.ResponseWriter:
  35. w = t
  36. case *http.Request:
  37. r = t
  38. case string:
  39. url = t
  40. }
  41. }
  42. if detect.IsServer() && (w == nil || r == nil) {
  43. return
  44. }
  45. if url == "" {
  46. return
  47. }
  48. switch {
  49. case detect.IsBrowser():
  50. ClientRedirect(url)
  51. case detect.IsServer():
  52. ServerRedirect(w, r, url)
  53. }
  54. }