github.com/google/go-safeweb@v0.0.0-20231219055052-64d8cfc90fbb/safehttp/server_test.go (about) 1 // Copyright 2020 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package safehttp 16 17 import ( 18 "bufio" 19 "bytes" 20 "net/http" 21 "net/http/httputil" 22 "testing" 23 "time" 24 25 "github.com/google/go-safeweb/internal/requesttesting" 26 "github.com/google/safehtml" 27 ) 28 29 func TestServer(t *testing.T) { 30 l := requesttesting.NewFakeListener() 31 defer l.Close() 32 33 mux := NewServeMuxConfig(nil).Mux() 34 mux.Handle("/", "GET", HandlerFunc(func(w ResponseWriter, r *IncomingRequest) Result { 35 return w.Write(safehtml.HTMLEscaped("response")) 36 })) 37 rtim := 10 * time.Second 38 s := Server{ 39 Mux: mux, 40 ReadTimeout: rtim, 41 } 42 go s.Serve(l) 43 defer s.Close() 44 45 req := []byte("GET / HTTP/1.1\r\nHost: pkg.go.dev\r\n\r\n") 46 if err := l.SendRequest(req); err != nil { 47 t.Fatalf("Sending request: %v", err) 48 } 49 50 respBuf := make([]byte, 1024) 51 n, err := l.ReadResponse(respBuf) 52 if err != nil { 53 t.Fatalf("Reading response: %v", err) 54 } 55 respBuf = respBuf[:n] 56 resp, err := http.ReadResponse(bufio.NewReader(bytes.NewReader(respBuf)), &http.Request{}) 57 resp.Header.Del("Date") // This will change every time 58 59 got, err := httputil.DumpResponse(resp, true) 60 if err != nil { 61 t.Errorf("Cannot dump Respnse: %v", err) 62 } 63 want := []byte("HTTP/1.1 200 OK\r\nContent-Length: 8\r\n" + 64 "Content-Type: text/html; charset=utf-8\r\n\r\nresponse") 65 66 if !bytes.Equal(got, want) { 67 t.Errorf("Respnse: got %q, want %q", got, want) 68 } 69 if s.srv.ReadTimeout != rtim { 70 t.Errorf("Builder did not set ReadTimeout: got %v want %v", s.srv.ReadTimeout, rtim) 71 } 72 if s.srv.WriteTimeout != 5*time.Second { 73 t.Errorf("Builder did not set WriteTimeout: got %v want %v", s.srv.WriteTimeout, 5*time.Second) 74 } 75 }