utils.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package githttp
  2. import (
  3. "compress/flate"
  4. "compress/gzip"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "strconv"
  9. "strings"
  10. "time"
  11. )
  12. // requestReader returns an io.ReadCloser
  13. // that will decode data if needed, depending on the
  14. // "content-encoding" header
  15. func requestReader(req *http.Request) (io.ReadCloser, error) {
  16. switch req.Header.Get("content-encoding") {
  17. case "gzip":
  18. return gzip.NewReader(req.Body)
  19. case "deflate":
  20. return flate.NewReader(req.Body), nil
  21. }
  22. // If no encoding, use raw body
  23. return req.Body, nil
  24. }
  25. // HTTP parsing utility functions
  26. func getServiceType(r *http.Request) string {
  27. service_type := r.FormValue("service")
  28. if s := strings.HasPrefix(service_type, "git-"); !s {
  29. return ""
  30. }
  31. return strings.Replace(service_type, "git-", "", 1)
  32. }
  33. // HTTP error response handling functions
  34. func renderMethodNotAllowed(w http.ResponseWriter, r *http.Request) {
  35. if r.Proto == "HTTP/1.1" {
  36. w.WriteHeader(http.StatusMethodNotAllowed)
  37. w.Write([]byte("Method Not Allowed"))
  38. } else {
  39. w.WriteHeader(http.StatusBadRequest)
  40. w.Write([]byte("Bad Request"))
  41. }
  42. }
  43. func renderNotFound(w http.ResponseWriter) {
  44. w.WriteHeader(http.StatusNotFound)
  45. w.Write([]byte("Not Found"))
  46. }
  47. func renderNoAccess(w http.ResponseWriter) {
  48. w.WriteHeader(http.StatusForbidden)
  49. w.Write([]byte("Forbidden"))
  50. }
  51. // Packet-line handling function
  52. func packetFlush() []byte {
  53. return []byte("0000")
  54. }
  55. func packetWrite(str string) []byte {
  56. s := strconv.FormatInt(int64(len(str)+4), 16)
  57. if len(s)%4 != 0 {
  58. s = strings.Repeat("0", 4-len(s)%4) + s
  59. }
  60. return []byte(s + str)
  61. }
  62. // Header writing functions
  63. func hdrNocache(w http.ResponseWriter) {
  64. w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
  65. w.Header().Set("Pragma", "no-cache")
  66. w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
  67. }
  68. func hdrCacheForever(w http.ResponseWriter) {
  69. now := time.Now().Unix()
  70. expires := now + 31536000
  71. w.Header().Set("Date", fmt.Sprintf("%d", now))
  72. w.Header().Set("Expires", fmt.Sprintf("%d", expires))
  73. w.Header().Set("Cache-Control", "public, max-age=31536000")
  74. }