Last active
February 26, 2020 00:49
-
-
Save nomkhonwaan/b7526527067b1069d73d3b991be8b93c to your computer and use it in GitHub Desktop.
unit-testing-กับแพคเกจ-valyala-fasthttp-5e40801aaf437cc917f05226
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"github.com/valyala/fasthttp" | |
) | |
func main() { | |
log.Println("fasthttp server is listening on :8080") | |
fasthttp.ListenAndServe(":8080", handle) | |
} | |
func handle(ctx *fasthttp.RequestCtx) { | |
switch string(ctx.Path()) { | |
case "/": | |
handleHomePage(ctx) | |
default: | |
ctx.Error(fasthttp.StatusMessage(fasthttp.StatusNotFound), fasthttp.StatusNotFound) | |
} | |
} | |
func handleHomePage(ctx *fasthttp.RequestCtx) { | |
ctx.WriteString("OK") | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"context" | |
"io/ioutil" | |
"net" | |
"net/http" | |
"testing" | |
"github.com/valyala/fasthttp" | |
"github.com/valyala/fasthttp/fasthttputil" | |
) | |
func TestHandleHomePage(t *testing.T) { | |
// Given | |
l := fasthttputil.NewInmemoryListener() | |
defer l.Close() | |
go func() { | |
fasthttp.Serve(l, handle) | |
}() | |
c := http.Client{ | |
Transport: &http.Transport{ | |
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) { | |
conn, _ := l.Dial() | |
return conn, nil | |
}, | |
}, | |
} | |
// When | |
req, _ := http.NewRequest(fasthttp.MethodPost, "http://localhost", nil) | |
res, err := c.Do(req) | |
// Then | |
if err != nil { | |
t.Errorf("expect err to be nil but got: %s", err) | |
} | |
data, _ := ioutil.ReadAll(res.Body) | |
defer res.Body.Close() | |
if bytes.Compare([]byte("OK"), data) != 0 { | |
t.Errorf("expect data to be %q but got: %s", "OK", data) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment