bridge.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2011 Andy Balholm. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // A bridge between ICAP and HTTP.
  5. // It allows answering a REQMOD request with an HTTP response generated locally.
  6. package icap
  7. import (
  8. "log"
  9. "net/http"
  10. "time"
  11. )
  12. type bridgedRespWriter struct {
  13. irw ResponseWriter // the underlying icap.ResponseWriter
  14. header http.Header // the headers for the HTTP response
  15. wroteHeader bool // Have the headers been written yet?
  16. }
  17. func (w *bridgedRespWriter) Header() http.Header {
  18. return w.header
  19. }
  20. func (w *bridgedRespWriter) Write(p []byte) (n int, err error) {
  21. if !w.wroteHeader {
  22. w.WriteHeader(http.StatusOK)
  23. }
  24. return w.irw.Write(p)
  25. }
  26. func (w *bridgedRespWriter) WriteHeader(code int) {
  27. if w.wroteHeader {
  28. log.Print("http: multiple response.WriteHeader calls")
  29. return
  30. }
  31. w.wroteHeader = true
  32. // Default output is HTML encoded in UTF-8.
  33. if w.header.Get("Content-Type") == "" {
  34. w.header.Set("Content-Type", "text/html; charset=utf-8")
  35. }
  36. if _, ok := w.header["Date"]; !ok {
  37. w.Header().Set("Date", time.Now().UTC().Format(http.TimeFormat))
  38. }
  39. resp := new(http.Response)
  40. resp.StatusCode = code
  41. resp.Header = w.header
  42. w.irw.WriteHeader(200, resp, true)
  43. }
  44. // NewBridgedResponseWriter Create an http.ResponseWriter that encapsulates its response in an ICAP response.
  45. func NewBridgedResponseWriter(w ResponseWriter) http.ResponseWriter {
  46. rw := new(bridgedRespWriter)
  47. rw.header = make(http.Header)
  48. rw.irw = w
  49. return rw
  50. }
  51. // ServeLocally Pass use the local HTTP server to generate a response for an ICAP request.
  52. func ServeLocally(w ResponseWriter, req *Request) {
  53. brw := NewBridgedResponseWriter(w)
  54. http.DefaultServeMux.ServeHTTP(brw, req.Request)
  55. }
  56. // ServeLocallyFromHandler ---
  57. func ServeLocallyFromHandler(w ResponseWriter, req *Request, mux http.Handler) {
  58. brw := NewBridgedResponseWriter(w)
  59. mux.ServeHTTP(brw, req.Request)
  60. }