cphelps
cphelps

Reputation: 93

Travis CI failing when trying to test Golang HTTP Server

I'm very new to travis and Go. I have a test for a https server and it runs fine with I run go test -v ./... on my local machine but it will fail most of the time on Travis due to a getsocketopt: connection refused error when trying to connect to the server. It should be listening on https://localhost:8081. Is there something in my .travis.yml I can do to prevent this from happening?

Here is my .travis.yml

language: go
go:
 - 1.6
 - tip
matrix:
  allow_failures:
 - go: tip
before_install:
 - go get -v github.com/golang/lint/golint
install:
 - go get -v -d -t ./...

Here's my server creation code:

func (webserver *WebServer) Start(keyLocation string, certLocation string) <-chan error {
    errors := make(chan error, 1)
    go func() {
        defer close(errors)
        errors <- http.ListenAndServeTLS(fmt.Sprintf(":%v", webserver.config.WebServerPort), certLocation, keyLocation, nil)
    }()
    return errors
}

And the client code:

func createHTTPClient(t *testing.T) *http.Client {
    t.Log("Creating a test client...")
    tr := &http.Transport {
        TLSClientConfig: &tls.Config {InsecureSkipVerify: true},
    }

    t.Log("Created a test client")
    return &http.Client {Transport: tr}
}

Sample request with client

request, _ := http.NewRequest(httpmethod, fmt.Sprintf("https://localhost:%d/token", port), nil)
client.Do(request)

Sample starting the server in a test

errors := server.Start(testKeyLocation, testCertLocation)
//Handle errors from server
go func() {
    select {
        case err := <-errors:
            if err != nil {
                t.Fatalf("Error with server: %s", err.Error())
            }
    }
}()

Upvotes: 0

Views: 806

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109367

You have no synchronization between starting the server and trying to connect. Adding a time.Sleep after starting the server should highlight the issue.

One way to reduce the window where the server isn't ready is to create the net.Listener synchronously, and then add the open listener to the http.Server config before starting the server. The httptest.Server can do this for you, as well as bind to random ports to prevent conflicts during tests, and using local test TLS certificates.

Upvotes: 3

Related Questions