11package main
22
33import (
4+ "fmt"
45 "net/http"
56 "strconv"
67
@@ -39,7 +40,7 @@ func NewSpinRedirect() SpinRedirect {
3940
4041func (s SpinRedirect ) handleFunc (w http.ResponseWriter , r * http.Request ) {
4142 dest := s .getDestination ()
42- code := s .getStatusCode ()
43+ code := s .getStatusCode (r . Method )
4344
4445 w .Header ().Set ("Location" , dest )
4546 w .WriteHeader (code )
@@ -54,11 +55,37 @@ func (s SpinRedirect) getDestination() string {
5455// getStatusCode returns the HTTP status code
5556// If no status code is found, or if the provided value is invalid,
5657// DefaultStatusCode is returned.
57- func (s SpinRedirect ) getStatusCode () int {
58+ func (s SpinRedirect ) getStatusCode (method string ) int {
5859 str := s .cfg .Get (statusCodeKey )
5960 code , err := strconv .Atoi (str )
6061 if err != nil {
6162 return DefaultStatusCode
6263 }
64+ if ! isValidRedirectStatusCode (code , method ) {
65+ fmt .Printf ("Invalid status code provided: %d. Will use %d instead.\n " , code , DefaultStatusCode )
66+ return DefaultStatusCode
67+ }
68+
6369 return code
6470}
71+
72+ // isValidRedirectStatusCode returns true if the provided status code is valid for redirection
73+ func isValidRedirectStatusCode (code int , method string ) bool {
74+ if code == http .StatusSeeOther &&
75+ (method == http .MethodPut || method == http .MethodPost ) {
76+ return true
77+ }
78+ validCodes := []int {
79+ http .StatusMovedPermanently ,
80+ http .StatusFound ,
81+ http .StatusTemporaryRedirect ,
82+ http .StatusPermanentRedirect ,
83+ }
84+
85+ for _ , c := range validCodes {
86+ if c == code {
87+ return true
88+ }
89+ }
90+ return false
91+ }
0 commit comments