home » torr/wssrv.git
ID: dfcddfbb8ec2389d26bb99d468b1565ac6b0d67b
86 lines — 1K — View raw


package main

import (
	"bufio"
	"fmt"
	"net"
	"net/http"
	"wssrv/ws"
	"wssrv/wshttp"

	"github.com/gorilla/websocket"
)

const (
	flagHost = "host"
	flagPort = "port"

	defHost   = "localhost"
	defPort   = 8070
	defBufSiz = 256
)

var (
	port   int = 8070
	stream bool
)

func acceptTcpCon(addr string) (net.Conn, error) {
	var (
		err error
		l   net.Listener
	)

	if l, err = net.Listen("tcp", addr); err != nil {
		return nil, err
	}
	return l.Accept()
}

func acceptWsCon(tCon net.Conn) *websocket.Conn {
	var (
		err  error
		req  *http.Request
		con  *websocket.Conn
		eMsg string

		r  = bufio.NewReader(tCon)
		rw = wshttp.NewResponse(tCon)
	)

	for con == nil {
		if req, err = http.ReadRequest(r); err != nil {
			eMsg = fmt.Sprintf("unable to read request: %v", err)
			logErr.Print(eMsg)
			http.Error(rw, fmt.Sprintf("error: %s", eMsg), http.StatusBadRequest)
			continue
		}

		if con, err = websocket.Upgrade(rw, req, nil, defBufSiz, defBufSiz); err != nil {
			eMsg = fmt.Sprintf("unable to create websocket connection: %v", err)
			logErr.Print(eMsg)
			http.Error(rw, fmt.Sprintf("error: %s", eMsg), http.StatusBadRequest)
		}
	}

	return con
}

func main() {
	var (
		err  error
		tCon net.Conn
		con  *websocket.Conn

		listenAddr = fmt.Sprintf("%s:%d", defHost, port)
	)

	logInfo.Printf("listening on '%s'", listenAddr)
	if tCon, err = acceptTcpCon(listenAddr); err != nil {
		panic(err)
	}
	con = acceptWsCon(tCon)
	defer con.Close()

	fmt.Println(ws.SendStdinLines(con))
}