April 28, 2016

customize golang tls listener

How ListenAndServeTLS works in Golang

  1. it creates a struct of http.Server type, and then calls the server.ListenAndServe method
  2. http.server.ListenAndServeTLS
    1. clone server.TLSConfig
    2. if tls config has no certs OR a certfile is specified, load certs
    3. create a TLS socket that listens on the TCP port
    4. call server.Serve using that socket
  3. Server.serve
    1. Accept the new connection, returns http.conn
    2. http.conn.serve()


The customize this, one could write his own function like this:

   srv := &Server{Addr: addr, Handler: handler}
    addr := srv.Addr
    if addr == "" {
        addr = ":https"
    }
    config := cloneTLSConfig(srv.TLSConfig)
    if config.NextProtos == nil {
        config.NextProtos = []string{"http/1.1"}
    }

    if len(config.Certificates) == 0 || certFile != "" || keyFile != "" {
        var err error
        config.Certificates = make([]tls.Certificate, 1)
        config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
        if err != nil {
            return err
        }
    }

    ln, err := net.Listen("tcp", addr)
    if err != nil {
        return err
    }

    tlsListener := tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, config)
    return srv.Serve(tlsListener)



No comments:

Post a Comment