|
1 | 1 | package main |
2 | 2 |
|
3 | 3 | import ( |
4 | | - "fmt" |
5 | | - "os" |
| 4 | + "net/http" |
| 5 | + "strconv" |
| 6 | + |
| 7 | + spinhttp "github.com/fermyon/spin/sdk/go/http" |
| 8 | +) |
| 9 | + |
| 10 | +const ( |
| 11 | + // Default value for HTTP status code |
| 12 | + DefaultStatusCode int = http.StatusFound |
| 13 | + // Key for loading desired destination |
| 14 | + destinationKey string = "destination" |
| 15 | + // Key for loading desired HTTP status code |
| 16 | + statusCodeKey string = "statuscode" |
6 | 17 | ) |
7 | 18 |
|
| 19 | +func init() { |
| 20 | + r := NewSpinRedirect() |
| 21 | + spinhttp.Handle(r.handleFunc) |
| 22 | +} |
| 23 | + |
8 | 24 | func main() { |
9 | | - dest := os.Getenv("DESTINATION") |
10 | | - fmt.Printf("status: 302\nlocation: %s\n\n", dest) |
| 25 | +} |
| 26 | + |
| 27 | +// SpinRedirect is a struct that provides a handleFunc |
| 28 | +// for redirecting to a destination URL using configurable HTTP status code. |
| 29 | +type SpinRedirect struct { |
| 30 | + cfg ConfigReader |
| 31 | +} |
| 32 | + |
| 33 | +// NewSpinRedirect returns a new SpinRedirect |
| 34 | +func NewSpinRedirect() SpinRedirect { |
| 35 | + return SpinRedirect{ |
| 36 | + cfg: NewDefaultConfigReader(), |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +func (s SpinRedirect) handleFunc(w http.ResponseWriter, r *http.Request) { |
| 41 | + dest := s.getDestination() |
| 42 | + code := s.getStatusCode() |
| 43 | + |
| 44 | + w.Header().Set("Location", dest) |
| 45 | + w.WriteHeader(code) |
| 46 | +} |
| 47 | + |
| 48 | +// getDestination returns the destination URL |
| 49 | +// If no destination is found, an empty string is returned. |
| 50 | +func (s SpinRedirect) getDestination() string { |
| 51 | + return s.cfg.Get(destinationKey) |
| 52 | +} |
| 53 | + |
| 54 | +// getStatusCode returns the HTTP status code |
| 55 | +// If no status code is found, or if the provided value is invalid, |
| 56 | +// DefaultStatusCode is returned. |
| 57 | +func (s SpinRedirect) getStatusCode() int { |
| 58 | + str := s.cfg.Get(statusCodeKey) |
| 59 | + code, err := strconv.Atoi(str) |
| 60 | + if err != nil { |
| 61 | + return DefaultStatusCode |
| 62 | + } |
| 63 | + return code |
11 | 64 | } |
0 commit comments