Skip to content

Instantly share code, notes, and snippets.

@niamtokik
Created February 17, 2017 14:39
Show Gist options
  • Save niamtokik/e6132e7ae0ec0537f4ba9e6b5776951d to your computer and use it in GitHub Desktop.
Save niamtokik/e6132e7ae0ec0537f4ba9e6b5776951d to your computer and use it in GitHub Desktop.
simple concurrent wrapper with channels support around go net module
package main
import "fmt"
import "sync"
import "net"
import "bufio"
type Controller struct {
fifo chan string
status chan string
}
func (c *Controller) Init() {
c.fifo = make(chan string)
c.status = make(chan string)
}
func test(c Controller, wg *sync.WaitGroup) {
for {
select {
case fifo := <- c.fifo :
fmt.Println("got fifo:", fifo)
case status := <- c.status:
fmt.Println("got status:", status)
wg.Done()
return
}
}
}
func keep_state(target string, control chan [2]string) {
conn, err := net.Dial("tcp", target)
if err != nil {
fmt.Println(err)
return
}
for {
select {
case c := <- control:
if c[0] == "exit" {
return
}
if c[0] == "send" {
fmt.Fprintf(conn, c[1])
data := bufio.NewReader(conn)
readData(data)
}
}
}
}
func readData(data *bufio.Reader) {
for {
b, err := data.ReadByte()
if err != nil {
return
}
fmt.Printf("%c", b)
}
}
type RemoteHost struct {
target string
wg *sync.WaitGroup
control chan [2]string
}
func (r *RemoteHost) Init(wg *sync.WaitGroup) *RemoteHost {
r.control = make(chan [2]string)
r.wg = wg
return r
}
func (r *RemoteHost) SetTarget(target string) *RemoteHost{
r.target = target
return r
}
func (r *RemoteHost) AddWait() *RemoteHost {
r.wg.Add(1)
return r
}
func (r *RemoteHost) Run() *RemoteHost{
go keep_state(r.target, r.control)
return r
}
func (r *RemoteHost) Send(m [2]string) *RemoteHost{
r.control <- m
return r
}
func main() {
var wg sync.WaitGroup
var r RemoteHost
r.Init(&wg)
r.SetTarget("google.fr:80")
r.Run()
r.Send([2]string{"send", "GET / HTTP/1.0\r\n\r\n"})
r.Send([2]string{"exit", ""})
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment