From b875991a49ac6d323c9c52c889429eb3b1642ef7 Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Fri, 14 Dec 2018 18:33:13 +0000 Subject: [PATCH] net/http/httptest: don't register a flag unless it looks like it's in use We shouldn't pollute people's flags with this debugging flag that was never really meant to be public. It's certainly not documented. So keep it for now, but don't register it unless it looks like it's in use (by looking at os.Args). Kinda gross, but less gross than before. Fixes #28619 Change-Id: I47498948a26a71ff36f9658a6d9dac73fd0a3016 Reviewed-on: https://go-review.googlesource.com/c/154217 Run-TryBot: Brad Fitzpatrick TryBot-Result: Gobot Gobot Reviewed-by: Andrew Bonventre --- src/net/http/httptest/server.go | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/src/net/http/httptest/server.go b/src/net/http/httptest/server.go index ebafc9999c6..b4e2e9266e6 100644 --- a/src/net/http/httptest/server.go +++ b/src/net/http/httptest/server.go @@ -53,10 +53,10 @@ type Server struct { } func newLocalListener() net.Listener { - if *serve != "" { - l, err := net.Listen("tcp", *serve) + if serveFlag != "" { + l, err := net.Listen("tcp", serveFlag) if err != nil { - panic(fmt.Sprintf("httptest: failed to listen on %v: %v", *serve, err)) + panic(fmt.Sprintf("httptest: failed to listen on %v: %v", serveFlag, err)) } return l } @@ -73,7 +73,25 @@ func newLocalListener() net.Listener { // this flag lets you run // go test -run=BrokenTest -httptest.serve=127.0.0.1:8000 // to start the broken server so you can interact with it manually. -var serve = flag.String("httptest.serve", "", "if non-empty, httptest.NewServer serves on this address and blocks") +// We only register this flag if it looks like the caller knows about it +// and is trying to use it as we don't want to pollute flags and this +// isn't really part of our API. Don't depend on this. +var serveFlag string + +func init() { + if strSliceContainsPrefix(os.Args, "-httptest.serve=") || strSliceContainsPrefix(os.Args, "--httptest.serve=") { + flag.StringVar(&serveFlag, "httptest.serve", "", "if non-empty, httptest.NewServer serves on this address and blocks.") + } +} + +func strSliceContainsPrefix(v []string, pre string) bool { + for _, s := range v { + if strings.HasPrefix(s, pre) { + return true + } + } + return false +} // NewServer starts and returns a new Server. // The caller should call Close when finished, to shut it down. @@ -107,7 +125,7 @@ func (s *Server) Start() { s.URL = "http://" + s.Listener.Addr().String() s.wrap() s.goServe() - if *serve != "" { + if serveFlag != "" { fmt.Fprintln(os.Stderr, "httptest: serving on", s.URL) select {} }