/example/redirect.go

https://code.google.com/p/go-icap/ · Go · 65 lines · 38 code · 6 blank · 21 comment · 2 complexity · 27854b49a14398f626d13859bb962149 MD5 · raw file

  1. /*
  2. An example of how to use go-icap.
  3. Run this program and Squid on the same machine.
  4. Put the following lines in squid.conf:
  5. icap_enable on
  6. icap_service service_req reqmod_precache icap://127.0.0.1:11344/golang
  7. adaptation_access service_req allow all
  8. (The ICAP server needs to be started before Squid is.)
  9. Set your browser to use the Squid proxy.
  10. Try browsing to http://gateway/ and http://java.com/
  11. */
  12. package main
  13. import (
  14. "code.google.com/p/go-icap"
  15. "fmt"
  16. "net/http"
  17. "os"
  18. )
  19. var ISTag = "\"GOLANG\""
  20. func main() {
  21. // Set the files to be made available under http://gateway/
  22. http.Handle("/", http.FileServer(http.Dir(os.Getenv("HOME")+"/Sites")))
  23. icap.HandleFunc("/golang", toGolang)
  24. icap.ListenAndServe(":11344", icap.HandlerFunc(toGolang))
  25. }
  26. func toGolang(w icap.ResponseWriter, req *icap.Request) {
  27. h := w.Header()
  28. h.Set("ISTag", ISTag)
  29. h.Set("Service", "Golang redirector")
  30. switch req.Method {
  31. case "OPTIONS":
  32. h.Set("Methods", "REQMOD")
  33. h.Set("Allow", "204")
  34. w.WriteHeader(200, nil, false)
  35. case "REQMOD":
  36. switch req.Request.Host {
  37. case "gateway":
  38. // Run a fake HTTP server called gateway.
  39. icap.ServeLocally(w, req)
  40. case "java.com", "www.java.com":
  41. // Redirect the user to a more interesting language.
  42. req.Request.Host = "golang.org"
  43. req.Request.URL.Host = "golang.org"
  44. w.WriteHeader(200, req.Request, false)
  45. // TODO: copy the body (if any) from the original request.
  46. default:
  47. // Return the request unmodified.
  48. w.WriteHeader(204, nil, false)
  49. }
  50. default:
  51. w.WriteHeader(405, nil, false)
  52. fmt.Println("Invalid request method")
  53. }
  54. }