github.com/profzone/eden-framework@v1.0.10/pkg/courier/httpx/redirect.go (about)

     1  package httpx
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"strings"
     7  )
     8  
     9  type IRedirect interface {
    10  	Redirect(host string) string
    11  	Status() int
    12  }
    13  
    14  func RedirectWithStatusMovedPermanently(uri string) *statusMovedPermanently {
    15  	return &statusMovedPermanently{
    16  		location: location(uri),
    17  	}
    18  }
    19  
    20  type statusMovedPermanently struct {
    21  	location
    22  }
    23  
    24  func (s *statusMovedPermanently) Status() int {
    25  	return http.StatusMovedPermanently
    26  }
    27  
    28  func RedirectWithStatusFound(uri string) *statusFound {
    29  	return &statusFound{
    30  		location: location(uri),
    31  	}
    32  }
    33  
    34  type statusFound struct {
    35  	location
    36  }
    37  
    38  func (s *statusFound) Status() int {
    39  	return http.StatusFound
    40  }
    41  
    42  func RedirectWithStatusSeeOther(uri string) *statusSeeOther {
    43  	return &statusSeeOther{
    44  		location: location(uri),
    45  	}
    46  }
    47  
    48  type statusSeeOther struct {
    49  	location
    50  }
    51  
    52  func (s *statusSeeOther) Status() int {
    53  	return http.StatusSeeOther
    54  }
    55  
    56  func RedirectWithStatusTemporaryRedirect(uri string) *statusTemporaryRedirect {
    57  	return &statusTemporaryRedirect{
    58  		location: location(uri),
    59  	}
    60  }
    61  
    62  type statusTemporaryRedirect struct {
    63  	location
    64  }
    65  
    66  func (s *statusTemporaryRedirect) Status() int {
    67  	return http.StatusTemporaryRedirect
    68  }
    69  
    70  func RedirectWithStatusPermanentRedirect(uri string) *statusPermanentRedirect {
    71  	return &statusPermanentRedirect{
    72  		location: location(uri),
    73  	}
    74  }
    75  
    76  type statusPermanentRedirect struct {
    77  	location
    78  }
    79  
    80  func (s *statusPermanentRedirect) Status() int {
    81  	return http.StatusPermanentRedirect
    82  }
    83  
    84  type location string
    85  
    86  func (r *location) Error() string {
    87  	return fmt.Sprintf("location : %s", r)
    88  }
    89  
    90  func (r *location) Redirect(host string) string {
    91  	u := string(*r)
    92  	if strings.HasPrefix(u, "/") {
    93  		u = host + u
    94  		if !strings.HasPrefix(u, "http") {
    95  			u = "http://" + u
    96  		}
    97  	}
    98  	return u
    99  }