github.com/google/go-safeweb@v0.0.0-20231219055052-64d8cfc90fbb/safehttp/dispatcher.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 "net/http" 18 19 // Dispatcher is responsible for writing a response received from the 20 // ResponseWriter to the underlying http.ResponseWriter. 21 // 22 // The implementation of a custom Dispatcher should be thoroughly reviewed by 23 // the security team to avoid introducing vulnerabilities. 24 type Dispatcher interface { 25 // Write writes a Response to the underlying http.ResponseWriter. 26 // 27 // Write is responsible for setting the Content-Type response header. If the 28 // Dispatcher doesn't set the HTTP response status code, the default 29 // behavior of http.ResponseWriter applies (i.e. 200 OK is set on first 30 // Write). 31 // 32 // It should return an error if the writing operation fails or if the 33 // provided Response should not be written to the http.ResponseWriter 34 // because it's unsafe. 35 Write(rw http.ResponseWriter, resp Response) error 36 37 // Error writes an ErrorResponse to the underlying http.ResponseWriter. 38 // 39 // Error is responsible for setting the Content-Type response header and the 40 // HTTP response status code. 41 // 42 // It should return an error if the writing operation fails. 43 // 44 // Error should always attempt to write a response, no matter what is the 45 // underlying type of resp. As a fallback, the Dispatcher can use WriteTextError. 46 Error(rw http.ResponseWriter, resp ErrorResponse) error 47 } 48 49 func writeTextError(rw http.ResponseWriter, resp ErrorResponse) { 50 http.Error(rw, http.StatusText(int(resp.Code())), int(resp.Code())) 51 }