main.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. package main
  2. import (
  3. "os"
  4. "log"
  5. "path"
  6. "net/url"
  7. "net/http"
  8. "io/ioutil"
  9. "strings"
  10. "encoding/json"
  11. "bytes"
  12. "html/template"
  13. )
  14. var config = Config{}
  15. func main() {
  16. defer func() {
  17. if r := recover(); r != nil {
  18. log.Fatalln("Exiting due to error:", r)
  19. os.Exit(1)
  20. }
  21. }()
  22. var err error
  23. // Processing template
  24. tmpl, err = template.New("index").Parse(index)
  25. if err != nil {
  26. panic(err)
  27. }
  28. // Reading configuration
  29. logFile, err := ioutil.ReadFile("config.json")
  30. if err != nil {
  31. panic(err)
  32. }
  33. err = json.Unmarshal(logFile, &config)
  34. if err !=nil {
  35. panic(err)
  36. }
  37. // Serving HTTP
  38. http.HandleFunc("/", router)
  39. err = http.ListenAndServe(config.Address, nil)
  40. if err != nil {
  41. panic(err)
  42. }
  43. log.Println("Listening on", config.Address)
  44. }
  45. func router(w http.ResponseWriter, r *http.Request) {
  46. defer func() {
  47. if rec := recover(); rec != nil {
  48. handleError(w, r, rec, "Internal Server Error", http.StatusInternalServerError)
  49. }
  50. }()
  51. if r.URL.Path == "/" {
  52. serveIndex(w, r)
  53. return
  54. }
  55. location, _ := path.Split(r.URL.Path)
  56. if location == "/" {
  57. serveDirectory(w, r)
  58. } else {
  59. serveFile(w, r)
  60. }
  61. }
  62. func handleError(w http.ResponseWriter, r *http.Request, err interface{}, message string, status int) {
  63. log.Println("Request error [", r.URL.Path, "]:", message + ":", err)
  64. w.WriteHeader(status)
  65. tmpl.ExecuteTemplate(w, "index", &Page{Title: message, Error: status})
  66. }
  67. func serveDirectory(w http.ResponseWriter, r *http.Request) {
  68. var page Page
  69. urlPath, err := url.QueryUnescape(r.URL.Path)
  70. if err !=nil {
  71. handleError(w,r, nil, "Invalid URL", http.StatusBadRequest)
  72. return
  73. }
  74. urlPath = strings.TrimLeft(urlPath, "/")
  75. configDir, exists := config.Directories[urlPath]
  76. if !exists {
  77. handleError(w,r, nil, "Directory do not exist", http.StatusNotFound)
  78. return
  79. }
  80. files, err := ioutil.ReadDir(configDir.Path)
  81. if err != nil {
  82. handleError(w,r, err, "Unable to read server directory", http.StatusForbidden)
  83. return
  84. }
  85. page = Page{Title: urlPath, Items: make([]Item, len(files))}
  86. for i, file := range files {
  87. // TODO: Support directories
  88. if file.IsDir() {
  89. continue
  90. }
  91. if !strings.HasSuffix(strings.ToLower(file.Name()), strings.ToLower(configDir.Extension)) {
  92. continue
  93. }
  94. page.Items[i] = Item{
  95. Name: file.Name(),
  96. URL: url.QueryEscape(urlPath + "/" + file.Name()),
  97. Size: file.Size(),
  98. Date: file.ModTime(),
  99. Valid: true,
  100. Directory: false,
  101. }
  102. }
  103. tmpl.ExecuteTemplate(w, "index", &page)
  104. }
  105. func serveFile(w http.ResponseWriter, r *http.Request) {
  106. urlPath, err := url.QueryUnescape(r.URL.Path)
  107. if err !=nil {
  108. handleError(w,r, nil, "Invalid URL", http.StatusBadRequest)
  109. return
  110. }
  111. urlPath = strings.TrimLeft(urlPath, "/")
  112. location, urlFile := path.Split(urlPath)
  113. configDir, exists := config.Directories[strings.TrimRight(location, "/")]
  114. if !exists {
  115. handleError(w,r, nil, "Directory do not exist", http.StatusNotFound)
  116. return
  117. }
  118. servedFile := path.Join(configDir.Path, urlFile)
  119. if _, err := os.Stat(servedFile); os.IsNotExist(err) {
  120. handleError(w,r, err, "File does not exist", http.StatusNotFound)
  121. return
  122. }
  123. if !strings.HasSuffix(strings.ToLower(urlFile), strings.ToLower(configDir.Extension)) {
  124. handleError(w,r, err, "File does not exist", http.StatusNotFound)
  125. return
  126. }
  127. q := r.URL.Query()
  128. if q.Get("tarball") == "1" {
  129. buf := new(bytes.Buffer)
  130. file, err := os.Open(servedFile)
  131. if err != nil {
  132. handleError(w, r, err, "Unable to serve file", http.StatusInternalServerError)
  133. return
  134. }
  135. err = compress(file, buf)
  136. if err != nil {
  137. handleError(w, r, err, "Unable to compress file", http.StatusInternalServerError)
  138. return
  139. }
  140. w.Header().Set("Content-Disposition", "attachment; filename=\""+urlFile+".tar.gz\"")
  141. w.Write(buf.Bytes())
  142. } else {
  143. file, err := ioutil.ReadFile(servedFile)
  144. if err != nil {
  145. handleError(w, r, err, "Unable to read file", http.StatusInternalServerError)
  146. return
  147. }
  148. // If request is not tarball - send raw file to browser not as attachment.
  149. //w.Header().Set("Content-Disposition", "attachment; filename=\""+urlFile+"\"")
  150. w.Write(file)
  151. }
  152. }
  153. func serveIndex(w http.ResponseWriter, r *http.Request) {
  154. page := Page{Title: "Index", Items: make([]Item, len(config.Directories))}
  155. i := 0
  156. for name, dir := range config.Directories {
  157. stat, err := os.Stat(dir.Path)
  158. if err == nil {
  159. page.Items[i].Date = stat.ModTime()
  160. }
  161. page.Items[i].Name = name
  162. page.Items[i].URL = url.QueryEscape(name)
  163. page.Items[i].Valid = true
  164. page.Items[i].Directory = true
  165. i++
  166. }
  167. tmpl.ExecuteTemplate(w, "index", &page)
  168. }