github.com/blend/go-sdk@v1.20220411.3/web/redirect_result.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package web 9 10 import ( 11 "fmt" 12 "net/http" 13 14 "github.com/blend/go-sdk/logger" 15 ) 16 17 // Redirect returns a redirect result to a given destination. 18 func Redirect(destination string) *RedirectResult { 19 return &RedirectResult{ 20 RedirectURI: destination, 21 } 22 } 23 24 // Redirectf returns a redirect result to a given destination specified by a given format and scan arguments. 25 func Redirectf(format string, args ...interface{}) *RedirectResult { 26 return &RedirectResult{ 27 RedirectURI: fmt.Sprintf(format, args...), 28 } 29 } 30 31 // RedirectWithMethod returns a redirect result to a destination with a given method. 32 func RedirectWithMethod(method, destination string) *RedirectResult { 33 return &RedirectResult{ 34 Method: method, 35 RedirectURI: destination, 36 } 37 } 38 39 // RedirectWithMethodf returns a redirect result to a destination composed of a format and scan arguments with a given method. 40 func RedirectWithMethodf(method, format string, args ...interface{}) *RedirectResult { 41 return &RedirectResult{ 42 Method: method, 43 RedirectURI: fmt.Sprintf(format, args...), 44 } 45 } 46 47 // RedirectResult is a result that should cause the browser to redirect. 48 type RedirectResult struct { 49 Method string `json:"redirect_method"` 50 RedirectURI string `json:"redirect_uri"` 51 } 52 53 // Render writes the result to the response. 54 func (rr *RedirectResult) Render(ctx *Ctx) error { 55 ctx.WithContext(logger.WithLabel(ctx.Context(), "web.redirect", rr.RedirectURI)) 56 if len(rr.Method) > 0 { 57 ctx.Request.Method = rr.Method 58 http.Redirect(ctx.Response, ctx.Request, rr.RedirectURI, http.StatusFound) 59 } else { 60 http.Redirect(ctx.Response, ctx.Request, rr.RedirectURI, http.StatusTemporaryRedirect) 61 } 62 return nil 63 }