Add NewRequestFromURL function

This commit is contained in:
Adnan Maolood 2020-10-27 13:27:52 -04:00
parent c44f011b15
commit 8ab4064841
2 changed files with 18 additions and 10 deletions

View File

@ -7,6 +7,7 @@ import (
"crypto/tls"
"crypto/x509"
"fmt"
"net/url"
"os"
"time"
@ -76,21 +77,23 @@ func sendRequest(req *gmi.Request) error {
case gmi.StatusClassInput:
fmt.Printf("%s: ", resp.Meta)
scanner.Scan()
req.URL.RawQuery = scanner.Text()
req.URL.RawQuery = url.QueryEscape(scanner.Text())
return sendRequest(req)
case gmi.StatusClassSuccess:
fmt.Print(string(resp.Body))
return nil
case gmi.StatusClassRedirect:
fmt.Println("Redirecting to", resp.Meta)
// Make the request to the same host
red, err := gmi.NewRequestTo(resp.Meta, req.Host)
target, err := url.Parse(resp.Meta)
if err != nil {
return err
}
// Handle relative redirects
red.URL = req.URL.ResolveReference(red.URL)
return sendRequest(red)
// TODO: Prompt the user if the redirect is to another domain.
redirect, err := gmi.NewRequestFromURL(req.URL.ResolveReference(target))
if err != nil {
return err
}
return sendRequest(redirect)
case gmi.StatusClassTemporaryFailure:
return fmt.Errorf("Temporary failure: %s", resp.Meta)
case gmi.StatusClassPermanentFailure:

View File

@ -42,22 +42,27 @@ func hostname(host string) string {
return hostname
}
// NewRequest returns a new request. The host is inferred from the provided URL.
// NewRequest returns a new request. The host is inferred from the URL.
func NewRequest(rawurl string) (*Request, error) {
u, err := url.Parse(rawurl)
if err != nil {
return nil, err
}
return NewRequestFromURL(u)
}
// NewRequestFromURL returns a new request for the given URL.
// The host is inferred from the URL.
func NewRequestFromURL(url *url.URL) (*Request, error) {
// If there is no port, use the default port of 1965
host := u.Host
if u.Port() == "" {
host := url.Host
if url.Port() == "" {
host += ":1965"
}
return &Request{
Host: host,
URL: u,
URL: url,
}, nil
}