// Copyright (c) 2022 Nadeen Udantha . All rights reserved. package boihttp_test import ( "bufio" "bytes" "context" "fmt" "io" "io/ioutil" "math/rand" "net" "strconv" "testing" "git.nadeen.lk/boihttp" ) func TestServer(t *testing.T) { l, err := net.Listen("tcp", "localhost:0") throw(err) go func() { err := boihttp.Serve(l, handler) if err != nil { fmt.Println(err) } }() url := fmt.Sprintf("http://localhost:%d/", l.Addr().(*net.TCPAddr).Port) c, err := net.Dial("tcp", l.Addr().String()) throw(err) rw := bufio.NewReadWriter(bufio.NewReader(c), bufio.NewWriter(c)) hdrs := make(boihttp.Headers) hdrs.Set("Connection", "keep-alive") for z := 4; z >= 0; z-- { if z == 0 { hdrs.Set("Connection", "close") } hdrs2 := hdrs.Clone() x := rand.Int() & 0xffff xx := strconv.Itoa(x) hdrs2.Set("x", xx) hdrs2.SetContentLength(len(xx)) res, resbody, err := boihttp.DoConn(rw, "POST", url, hdrs2, bytes.NewBufferString(xx)) throw(err) y, err := strconv.Atoi(res.Get("y")) throw(err) if x*x != y { panic("wtf?") } yy, err := ioutil.ReadAll(resbody) throw(err) y, err = strconv.Atoi(string(yy)) throw(err) if x*x != y { panic("wtf?") } } } func handler(req *boihttp.Message, reqbody io.Reader, res *boihttp.Message) (resbody io.Reader) { x, err := strconv.Atoi(req.Get("x")) throw(err) xx, err := ioutil.ReadAll(reqbody) throw(err) x2, err := strconv.Atoi(string(xx)) throw(err) if x != x2 { panic("wtf") } y := strconv.Itoa(x * x) res.Set("y", y) res.SetContentLength(len(y)) return bytes.NewBufferString(y) } func TestServer2(t *testing.T) { go boihttp.Listen("localhost:8080", context.Background(), func(req *boihttp.Message, reqbody io.Reader, res *boihttp.Message) (resbody io.Reader) { res.SetStatus(200, "Noice") res.Set("working", "true") res.SetContentLength(3) return bytes.NewBufferString("lol") }) res, body, err := boihttp.Get("http://localhost:8080/", nil, context.Background()) throw(err) print(res, body) }