Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

-status-codes flag #59

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 22 additions & 13 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import (
"bufio"
"crypto/tls"
"flag"
"fmt"
"io"
"io/ioutil"
"fmt"
"net"
"net/http"
"os"
Expand Down Expand Up @@ -48,6 +48,10 @@ func main() {
var preferHTTPS bool
flag.BoolVar(&preferHTTPS, "prefer-https", false, "only try plain HTTP if HTTPS fails")

// show status codes
var showStatusCodes bool
flag.BoolVar(&showStatusCodes, "status-codes", false, "show status codes in output")

// HTTP method to use
var method string
flag.StringVar(&method, "method", "GET", "HTTP method to use")
Expand Down Expand Up @@ -96,8 +100,13 @@ func main() {

// always try HTTPS first
withProto := "https://" + url
if isListening(client, withProto, method) {
output <- withProto
if code, ok := isListening(client, withProto, method); ok {
if showStatusCodes {
output <- fmt.Sprintf("%d %s", code, withProto)
} else {
output <- withProto
}


// skip trying HTTP if --prefer-https is set
if preferHTTPS {
Expand All @@ -120,8 +129,12 @@ func main() {
go func() {
for url := range httpURLs {
withProto := "http://" + url
if isListening(client, withProto, method) {
output <- withProto
if code, ok := isListening(client, withProto, method); ok {
if showStatusCodes {
output <- fmt.Sprintf("%d %s", code, withProto)
} else {
output <- withProto
}
continue
}
}
Expand Down Expand Up @@ -210,11 +223,10 @@ func main() {
outputWG.Wait()
}

func isListening(client *http.Client, url, method string) bool {

func isListening(client *http.Client, url string, method string) (int, bool) {
req, err := http.NewRequest(method, url, nil)
if err != nil {
return false
return 0, false
}

req.Header.Add("Connection", "close")
Expand All @@ -224,11 +236,8 @@ func isListening(client *http.Client, url, method string) bool {
if resp != nil {
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
return resp.StatusCode, true
}

if err != nil {
return false
}

return true
return 0, false
}