package web_tests import ( "bytes" "compress/gzip" "io" "reflect" "testing" web "git.sharkk.net/Go/Web" ) func TestWrite(t *testing.T) { s := web.NewServer() s.Get("/", func(ctx web.Context) error { _, err := ctx.Response().Write([]byte("Hello")) return err }) response := s.Request("GET", "/", nil, nil) if response.Status() != 200 { t.Error(response.Status()) } if string(response.Body()) != "Hello" { t.Error(string(response.Body())) } } func TestWriteString(t *testing.T) { s := web.NewServer() s.Get("/", func(ctx web.Context) error { _, err := io.WriteString(ctx.Response(), "Hello") return err }) response := s.Request("GET", "/", nil, nil) if response.Status() != 200 { t.Error(response.Status()) } if string(response.Body()) != "Hello" { t.Error(string(response.Body())) } } func TestResponseCompression(t *testing.T) { s := web.NewServer() uncompressed := bytes.Repeat([]byte("This text should be compressed to a size smaller than the original."), 5) s.Use(func(ctx web.Context) error { defer func() { body := ctx.Response().Body() ctx.Response().SetBody(nil) zip := gzip.NewWriter(ctx.Response()) zip.Write(body) zip.Close() }() return ctx.Next() }) s.Get("/", func(ctx web.Context) error { return ctx.Bytes(uncompressed) }) response := s.Request("GET", "/", nil, nil) if response.Status() != 200 { t.Error(response.Status()) } if len(response.Body()) >= len(uncompressed) { t.Error("Response is larger than original") } reader, err := gzip.NewReader(bytes.NewReader(response.Body())) if err != nil { t.Error(err) } decompressed, err := io.ReadAll(reader) if err != nil { t.Error(err) } if !reflect.DeepEqual(decompressed, uncompressed) { t.Error(string(decompressed)) } } func TestResponseHeader(t *testing.T) { s := web.NewServer() s.Get("/", func(ctx web.Context) error { ctx.Response().SetHeader("Content-Type", "text/plain") contentType := ctx.Response().Header("Content-Type") return ctx.String(contentType) }) response := s.Request("GET", "/", nil, nil) if response.Status() != 200 { t.Error(response.Status()) } if response.Header("Content-Type") != "text/plain" { t.Error(response.Header("Content-Type")) } if response.Header("Non existent header") != "" { t.Error(response.Header("Non existent header")) } if string(response.Body()) != "text/plain" { t.Error(string(response.Body())) } } func TestResponseHeaderOverwrite(t *testing.T) { s := web.NewServer() s.Get("/", func(ctx web.Context) error { ctx.Response().SetHeader("Content-Type", "text/plain") ctx.Response().SetHeader("Content-Type", "text/html") return nil }) response := s.Request("GET", "/", nil, nil) if response.Status() != 200 { t.Error(response.Status()) } if response.Header("Content-Type") != "text/html" { t.Error(response.Header("Content-Type")) } if string(response.Body()) != "" { t.Error(string(response.Body())) } }