main.go 4.6 KB

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