We can achieve page-to-page redirection through RedirectTo/RedirectBack, which is implemented via Location Header. Relevant methods:

  1. func (r *Response) RedirectBack(code ...int)
  2. func (r *Response) RedirectTo(location string, code ...int)

RedirectTo

RedirectTo is used to guide the client to a specified address, which can be a relative path of a local service or a complete HTTP address. Usage example:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. func main() {
  7. s := g.Server()
  8. s.BindHandler("/", func(r *ghttp.Request) {
  9. r.Response.RedirectTo("/login")
  10. })
  11. s.BindHandler("/login", func(r *ghttp.Request) {
  12. r.Response.Writeln("Login First")
  13. })
  14. s.SetPort(8199)
  15. s.Run()
  16. }

After running, we access http://127.0.0.1:8199/ through the browser and you will find that the browser immediately redirects to the page http://127.0.0.1:8199/login.

RedirectBack

RedirectBack is used to guide the client back to the previous page address, which is obtained through the Referer Header. Usually, browser clients will pass this Header. Usage example:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. func main() {
  7. s := g.Server()
  8. s.BindHandler("/page", func(r *ghttp.Request) {
  9. r.Response.Writeln(`<a href="/back">back</a>`)
  10. })
  11. s.BindHandler("/back", func(r *ghttp.Request) {
  12. r.Response.RedirectBack()
  13. })
  14. s.SetPort(8199)
  15. s.Run()
  16. }

After running, we access http://127.0.0.1:8199/page through the browser and click the back link on the page. You can observe that after clicking, the page redirects back.