github.com/google/go-safeweb@v0.0.0-20231219055052-64d8cfc90fbb/safehttp/handler.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 // Handler responds to an HTTP request. 18 type Handler interface { 19 // ServeHTTP writes the response exactly once, returning the result 20 // 21 // Except for reading the body, handlers should not modify the provided Request. 22 // 23 // TODO: Add documentation about error handling when properly implemented. 24 ServeHTTP(ResponseWriter, *IncomingRequest) Result 25 } 26 27 // HandlerFunc is used to convert a function into a Handler. 28 type HandlerFunc func(ResponseWriter, *IncomingRequest) Result 29 30 // ServeHTTP calls f(w, r). 31 func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *IncomingRequest) Result { 32 return f(w, r) 33 } 34 35 // StripPrefix returns a handler that serves HTTP requests by removing the given 36 // prefix from the request URL's Path (and RawPath if set) and invoking the 37 // handler h. 38 // 39 // StripPrefix handles a request for a path that doesn't begin with prefix by 40 // panicking, as this is a server configuration error. The prefix must match 41 // exactly (e.g. escaped and unescaped characters are considered different). 42 func StripPrefix(prefix string, h Handler) Handler { 43 if prefix == "" { 44 return h 45 } 46 return HandlerFunc(func(rw ResponseWriter, ir *IncomingRequest) Result { 47 ir2, err := ir.WithStrippedURLPrefix(prefix) 48 if err != nil { 49 panic(err) 50 } 51 return h.ServeHTTP(rw, ir2) 52 }) 53 }