Skip to content

Latest commit

 

History

History

085-TCP-Server

HTTP Server

HTTP uses TCP.

To create a server that works with HTTP, we just create a TCP server.

To configure our code to handle request/response in an HTTP fashion which works with browsers, we need to adhere to HTTP standards.

TCP server essentials

Listen

net.Listen

func Listen(net, laddr string) (Listener, error)

Listener

net.Listener

type Listener interface {
    // Accept waits for and returns the next connection to the listener.
    Accept() (Conn, error)

    // Close closes the listener.
    // Any blocked Accept operations will be unblocked and return errors.
    Close() error

    // Addr returns the listener's network address.
    Addr() Addr
}

Connection

net.Conn

type Conn interface {
    // Read reads data from the connection.
    Read(b []byte) (n int, err error)

    // Write writes data to the connection.
    Write(b []byte) (n int, err error)

    // Close closes the connection.
    // Any blocked Read or Write operations will be unblocked and return errors.
    Close() error

    // LocalAddr returns the local network address.
    LocalAddr() Addr

    // RemoteAddr returns the remote network address.
    RemoteAddr() Addr

    SetDeadline(t time.Time) error

    SetReadDeadline(t time.Time) error

    SetWriteDeadline(t time.Time) error
}

Dial

net.Dial

func Dial(network, address string) (Conn, error)

Write

io.WriteString

func WriteString(w Writer, s string) (n int, err error)

fmt.Fprintln

func Fprintln(w io.Writer, a ...interface{}) (n int, err error)

Read

func ReadAll(r io.Reader) ([]byte, error)
func NewScanner(r io.Reader) *Scanner
func (s *Scanner) Scan() bool
func (s *Scanner) Text() string

Read & Write

func Copy(dst Writer, src Reader) (written int64, err error)