Fix panic when SERVER_STARTER_PORT is not defined #3

Merged
merged 1 commit into from May 11, 2015

Projects

None yet

2 participants

@handlename
Contributor

I want to run app with Server::Starter and without it in same code.
So I wrote code like below.

package main

import (
    "fmt"
    "net"
    "net/http"

    "github.com/lestrrat/go-server-starter/listener"
)

func main() {
    listeners, err := listener.ListenAll()
    if err != nil {
        fmt.Println(err)
        return
    }

    var l net.Listener
    if len(listeners) == 0 {
        l, err = net.Listen("tcp", ":8080")
    } else {
        l = listeners[0]
    }

    fmt.Println(http.Serve(l, nil))
}

But this code will panic

panic: runtime error: index out of range

goroutine 1 [running]:
github.com/lestrrat/go-server-starter/listener.parseListenTargets(0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0)
    /Users/nagata-hiroaki/src/github.com/lestrrat/go-server-starter/listener/listener.go:91 +0x8bd
github.com/lestrrat/go-server-starter/listener.ListenAll(0x0, 0x0, 0x0, 0x0, 0x0)
    /Users/nagata-hiroaki/src/github.com/lestrrat/go-server-starter/listener/listener.go:144 +0x8a
main.main()
    /Users/nagata-hiroaki/junk/2015/05/20150508_200547_server_starter/main.go:12 +0x27

goroutine 2 [runnable]:
runtime.forcegchelper()
    /usr/local/Cellar/go/1.4.2/libexec/src/runtime/proc.go:90
runtime.goexit()
    /usr/local/Cellar/go/1.4.2/libexec/src/runtime/asm_amd64.s:2232 +0x1

goroutine 3 [runnable]:
runtime.bgsweep()
    /usr/local/Cellar/go/1.4.2/libexec/src/runtime/mgc0.go:82
runtime.goexit()
    /usr/local/Cellar/go/1.4.2/libexec/src/runtime/asm_amd64.s:2232 +0x1

goroutine 4 [runnable]:
runtime.runfinq()
    /usr/local/Cellar/go/1.4.2/libexec/src/runtime/malloc.go:712
runtime.goexit()
    /usr/local/Cellar/go/1.4.2/libexec/src/runtime/asm_amd64.s:2232 +0x1
exit status 2

This Pull Request fix it.

@handlename
Contributor

Or should I write like this?

package main

import (
    "fmt"
    "net"
    "net/http"
    "os"

    "github.com/lestrrat/go-server-starter/listener"
)

func main() {
    var l net.Listener

    // check environment variable
    if os.Getenv("SERVER_STARTER_PORT") != "" {
        listeners, err := listener.ListenAll()
        if err != nil {
            fmt.Println(err)
            return
        }

        if 0 < len(listeners) {
            l = listeners[0]
        }
    }

    if l == nil {
        var err error
        l, err = net.Listen("tcp", fmt.Sprintf(":8080"))

        if err != nil {
            fmt.Println(err)
            return
        }
    }

    fmt.Println(http.Serve(l, nil))
}
@lestrrat
Owner

I think I like your change :)

@lestrrat lestrrat merged commit 7f46eb4 into lestrrat:master May 11, 2015
@handlename
Contributor

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment