Disabling the HTTP connection keep-alive may help for this situation by 
calling: `srv.SetKeepAlivesEnabled(false)` and get the expected output 
**sometimes**

$ go run a.go
In handler wrapper, f = 0xc4200111a0
1
In handler wrapper, f = 0xc4200111a8
2

Though,  it’s strange that you’ll still need to Sleep some time to make sure 
the first server is cleaned properly.

package main

import (
  "fmt"
  "io/ioutil"
  "net"
  "net/http"
  "os"
  "strconv"
)

// Some state so we can show the old handler is in effect...
type Foo struct {
  SomeVar int
}

func (f *Foo) Serve(addr string) (net.Listener, error) {
  l, err := net.Listen("tcp", addr)
  if err != nil {
    return nil, err
  }
  mux := http.NewServeMux()
  mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Printf("In handler wrapper, f = %p\n", f)
    w.Write([]byte(strconv.Itoa(f.SomeVar)))
  })
  srv := &http.Server{
    Handler: mux,
  }
  srv.SetKeepAlivesEnabled(false)

  go srv.Serve(l)
  return l, nil
}

func main() {
  f1 := &Foo{SomeVar: 1}
  f2 := &Foo{SomeVar: 2}

  l, err := f1.Serve("0.0.0.0:8090")
  if err != nil {
    fmt.Println(err)
    os.Exit(1)
  }
  fmt.Println(doRequest())
  l.Close()
  // Ok it didn't actually close, wait a bit or it'll show the address as
  // already in use...
  // time.Sleep(1 * time.Second)

  l, err = f2.Serve("0.0.0.0:8090")
  if err != nil {
    fmt.Println(err)
    os.Exit(1)
  }
  fmt.Println(doRequest())
  l.Close()
}

func doRequest() string {
  client := &http.Client{}
  req, _ := http.NewRequest("GET", "http://0.0.0.0:8090";, nil)
  resp, _ := client.Do(req)
  bytes, _ := ioutil.ReadAll(resp.Body)
  return string(bytes)
}


> On Apr 18, 2017, at 11:48, Ken Simon <ninke...@gmail.com> wrote:
> 
> srv := &http.Server{
>               Handler: mux,
>       }

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Attachment: signature.asc
Description: Message signed with OpenPGP

Reply via email to