gui.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. // All rights reserved. Use of this source code is governed by an MIT-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. import (
  6. "bytes"
  7. "encoding/base64"
  8. "encoding/json"
  9. "fmt"
  10. "io/ioutil"
  11. "log"
  12. "math/rand"
  13. "mime"
  14. "net"
  15. "net/http"
  16. "os"
  17. "path/filepath"
  18. "reflect"
  19. "runtime"
  20. "strconv"
  21. "strings"
  22. "sync"
  23. "time"
  24. "crypto/tls"
  25. "code.google.com/p/go.crypto/bcrypt"
  26. "github.com/syncthing/syncthing/auto"
  27. "github.com/syncthing/syncthing/config"
  28. "github.com/syncthing/syncthing/events"
  29. "github.com/syncthing/syncthing/logger"
  30. "github.com/syncthing/syncthing/model"
  31. "github.com/syncthing/syncthing/protocol"
  32. "github.com/syncthing/syncthing/upgrade"
  33. "github.com/vitrun/qart/qr"
  34. )
  35. type guiError struct {
  36. Time time.Time
  37. Error string
  38. }
  39. var (
  40. configInSync = true
  41. guiErrors = []guiError{}
  42. guiErrorsMut sync.Mutex
  43. static func(http.ResponseWriter, *http.Request, *log.Logger)
  44. apiKey string
  45. modt = time.Now().UTC().Format(http.TimeFormat)
  46. eventSub *events.BufferedSubscription
  47. )
  48. const (
  49. unchangedPassword = "--password-unchanged--"
  50. )
  51. func init() {
  52. l.AddHandler(logger.LevelWarn, showGuiError)
  53. sub := events.Default.Subscribe(^events.EventType(events.ItemStarted | events.ItemCompleted))
  54. eventSub = events.NewBufferedSubscription(sub, 1000)
  55. }
  56. func startGUI(cfg config.GUIConfiguration, assetDir string, m *model.Model) error {
  57. var listener net.Listener
  58. var err error
  59. if cfg.UseTLS {
  60. cert, err := loadCert(confDir, "https-")
  61. if err != nil {
  62. l.Infoln("Loading HTTPS certificate:", err)
  63. l.Infoln("Creating new HTTPS certificate")
  64. newCertificate(confDir, "https-")
  65. cert, err = loadCert(confDir, "https-")
  66. }
  67. if err != nil {
  68. return err
  69. }
  70. tlsCfg := &tls.Config{
  71. Certificates: []tls.Certificate{cert},
  72. ServerName: "syncthing",
  73. }
  74. listener, err = tls.Listen("tcp", cfg.Address, tlsCfg)
  75. if err != nil {
  76. return err
  77. }
  78. } else {
  79. listener, err = net.Listen("tcp", cfg.Address)
  80. if err != nil {
  81. return err
  82. }
  83. }
  84. apiKey = cfg.APIKey
  85. loadCsrfTokens()
  86. // The GET handlers
  87. getRestMux := http.NewServeMux()
  88. getRestMux.HandleFunc("/rest/completion", withModel(m, restGetCompletion))
  89. getRestMux.HandleFunc("/rest/config", restGetConfig)
  90. getRestMux.HandleFunc("/rest/config/sync", restGetConfigInSync)
  91. getRestMux.HandleFunc("/rest/connections", withModel(m, restGetConnections))
  92. getRestMux.HandleFunc("/rest/discovery", restGetDiscovery)
  93. getRestMux.HandleFunc("/rest/errors", restGetErrors)
  94. getRestMux.HandleFunc("/rest/events", restGetEvents)
  95. getRestMux.HandleFunc("/rest/lang", restGetLang)
  96. getRestMux.HandleFunc("/rest/model", withModel(m, restGetModel))
  97. getRestMux.HandleFunc("/rest/model/version", withModel(m, restGetModelVersion))
  98. getRestMux.HandleFunc("/rest/need", withModel(m, restGetNeed))
  99. getRestMux.HandleFunc("/rest/nodeid", restGetNodeID)
  100. getRestMux.HandleFunc("/rest/report", withModel(m, restGetReport))
  101. getRestMux.HandleFunc("/rest/system", restGetSystem)
  102. getRestMux.HandleFunc("/rest/upgrade", restGetUpgrade)
  103. getRestMux.HandleFunc("/rest/version", restGetVersion)
  104. // Debug endpoints, not for general use
  105. getRestMux.HandleFunc("/rest/debug/peerCompletion", withModel(m, restGetPeerCompletion))
  106. // The POST handlers
  107. postRestMux := http.NewServeMux()
  108. postRestMux.HandleFunc("/rest/config", withModel(m, restPostConfig))
  109. postRestMux.HandleFunc("/rest/discovery/hint", restPostDiscoveryHint)
  110. postRestMux.HandleFunc("/rest/error", restPostError)
  111. postRestMux.HandleFunc("/rest/error/clear", restClearErrors)
  112. postRestMux.HandleFunc("/rest/model/override", withModel(m, restPostOverride))
  113. postRestMux.HandleFunc("/rest/reset", restPostReset)
  114. postRestMux.HandleFunc("/rest/restart", restPostRestart)
  115. postRestMux.HandleFunc("/rest/shutdown", restPostShutdown)
  116. postRestMux.HandleFunc("/rest/upgrade", restPostUpgrade)
  117. // A handler that splits requests between the two above and disables
  118. // caching
  119. restMux := noCacheMiddleware(getPostHandler(getRestMux, postRestMux))
  120. // The main routing handler
  121. mux := http.NewServeMux()
  122. mux.Handle("/rest/", restMux)
  123. mux.HandleFunc("/qr/", getQR)
  124. // Serve compiled in assets unless an asset directory was set (for development)
  125. mux.Handle("/", embeddedStatic(assetDir))
  126. // Wrap everything in CSRF protection. The /rest prefix should be
  127. // protected, other requests will grant cookies.
  128. handler := csrfMiddleware("/rest", mux)
  129. // Wrap everything in basic auth, if user/password is set.
  130. if len(cfg.User) > 0 {
  131. handler = basicAuthMiddleware(cfg.User, cfg.Password, handler)
  132. }
  133. go http.Serve(listener, handler)
  134. return nil
  135. }
  136. func getPostHandler(get, post http.Handler) http.Handler {
  137. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  138. switch r.Method {
  139. case "GET":
  140. get.ServeHTTP(w, r)
  141. case "POST":
  142. post.ServeHTTP(w, r)
  143. default:
  144. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  145. }
  146. })
  147. }
  148. func noCacheMiddleware(h http.Handler) http.Handler {
  149. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  150. w.Header().Set("Cache-Control", "no-cache")
  151. h.ServeHTTP(w, r)
  152. })
  153. }
  154. func withModel(m *model.Model, h func(m *model.Model, w http.ResponseWriter, r *http.Request)) http.HandlerFunc {
  155. return func(w http.ResponseWriter, r *http.Request) {
  156. h(m, w, r)
  157. }
  158. }
  159. func restGetVersion(w http.ResponseWriter, r *http.Request) {
  160. w.Write([]byte(Version))
  161. }
  162. func restGetCompletion(m *model.Model, w http.ResponseWriter, r *http.Request) {
  163. var qs = r.URL.Query()
  164. var repo = qs.Get("repo")
  165. var nodeStr = qs.Get("node")
  166. node, err := protocol.NodeIDFromString(nodeStr)
  167. if err != nil {
  168. http.Error(w, err.Error(), 500)
  169. return
  170. }
  171. res := map[string]float64{
  172. "completion": m.Completion(node, repo),
  173. }
  174. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  175. json.NewEncoder(w).Encode(res)
  176. }
  177. func restGetModelVersion(m *model.Model, w http.ResponseWriter, r *http.Request) {
  178. var qs = r.URL.Query()
  179. var repo = qs.Get("repo")
  180. var res = make(map[string]interface{})
  181. res["version"] = m.LocalVersion(repo)
  182. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  183. json.NewEncoder(w).Encode(res)
  184. }
  185. func restGetModel(m *model.Model, w http.ResponseWriter, r *http.Request) {
  186. var qs = r.URL.Query()
  187. var repo = qs.Get("repo")
  188. var res = make(map[string]interface{})
  189. for _, cr := range cfg.Repositories {
  190. if cr.ID == repo {
  191. res["invalid"] = cr.Invalid
  192. break
  193. }
  194. }
  195. globalFiles, globalDeleted, globalBytes := m.GlobalSize(repo)
  196. res["globalFiles"], res["globalDeleted"], res["globalBytes"] = globalFiles, globalDeleted, globalBytes
  197. localFiles, localDeleted, localBytes := m.LocalSize(repo)
  198. res["localFiles"], res["localDeleted"], res["localBytes"] = localFiles, localDeleted, localBytes
  199. needFiles, needBytes := m.NeedSize(repo)
  200. res["needFiles"], res["needBytes"] = needFiles, needBytes
  201. res["inSyncFiles"], res["inSyncBytes"] = globalFiles-needFiles, globalBytes-needBytes
  202. res["state"], res["stateChanged"] = m.State(repo)
  203. res["version"] = m.LocalVersion(repo)
  204. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  205. json.NewEncoder(w).Encode(res)
  206. }
  207. func restPostOverride(m *model.Model, w http.ResponseWriter, r *http.Request) {
  208. var qs = r.URL.Query()
  209. var repo = qs.Get("repo")
  210. m.Override(repo)
  211. }
  212. func restGetNeed(m *model.Model, w http.ResponseWriter, r *http.Request) {
  213. var qs = r.URL.Query()
  214. var repo = qs.Get("repo")
  215. files := m.NeedFilesRepo(repo)
  216. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  217. json.NewEncoder(w).Encode(files)
  218. }
  219. func restGetConnections(m *model.Model, w http.ResponseWriter, r *http.Request) {
  220. var res = m.ConnectionStats()
  221. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  222. json.NewEncoder(w).Encode(res)
  223. }
  224. func restGetConfig(w http.ResponseWriter, r *http.Request) {
  225. encCfg := cfg
  226. if encCfg.GUI.Password != "" {
  227. encCfg.GUI.Password = unchangedPassword
  228. }
  229. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  230. json.NewEncoder(w).Encode(encCfg)
  231. }
  232. func restPostConfig(m *model.Model, w http.ResponseWriter, r *http.Request) {
  233. var newCfg config.Configuration
  234. err := json.NewDecoder(r.Body).Decode(&newCfg)
  235. if err != nil {
  236. l.Warnln(err)
  237. } else {
  238. if newCfg.GUI.Password == "" {
  239. // Leave it empty
  240. } else if newCfg.GUI.Password == unchangedPassword {
  241. newCfg.GUI.Password = cfg.GUI.Password
  242. } else {
  243. hash, err := bcrypt.GenerateFromPassword([]byte(newCfg.GUI.Password), 0)
  244. if err != nil {
  245. l.Warnln(err)
  246. } else {
  247. newCfg.GUI.Password = string(hash)
  248. }
  249. }
  250. // Figure out if any changes require a restart
  251. if len(cfg.Repositories) != len(newCfg.Repositories) {
  252. configInSync = false
  253. } else {
  254. om := cfg.RepoMap()
  255. nm := newCfg.RepoMap()
  256. for id := range om {
  257. if !reflect.DeepEqual(om[id], nm[id]) {
  258. configInSync = false
  259. break
  260. }
  261. }
  262. }
  263. if len(cfg.Nodes) != len(newCfg.Nodes) {
  264. configInSync = false
  265. } else {
  266. om := cfg.NodeMap()
  267. nm := newCfg.NodeMap()
  268. for k := range om {
  269. if _, ok := nm[k]; !ok {
  270. // A node was removed and another added
  271. configInSync = false
  272. break
  273. }
  274. }
  275. }
  276. if newCfg.Options.URAccepted > cfg.Options.URAccepted {
  277. // UR was enabled
  278. newCfg.Options.URAccepted = usageReportVersion
  279. err := sendUsageReport(m)
  280. if err != nil {
  281. l.Infoln("Usage report:", err)
  282. }
  283. go usageReportingLoop(m)
  284. } else if newCfg.Options.URAccepted < cfg.Options.URAccepted {
  285. // UR was disabled
  286. newCfg.Options.URAccepted = -1
  287. stopUsageReporting()
  288. }
  289. if !reflect.DeepEqual(cfg.Options, newCfg.Options) || !reflect.DeepEqual(cfg.GUI, newCfg.GUI) {
  290. configInSync = false
  291. }
  292. // Activate and save
  293. cfg = newCfg
  294. saveConfig()
  295. }
  296. }
  297. func restGetConfigInSync(w http.ResponseWriter, r *http.Request) {
  298. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  299. json.NewEncoder(w).Encode(map[string]bool{"configInSync": configInSync})
  300. }
  301. func restPostRestart(w http.ResponseWriter, r *http.Request) {
  302. flushResponse(`{"ok": "restarting"}`, w)
  303. go restart()
  304. }
  305. func restPostReset(w http.ResponseWriter, r *http.Request) {
  306. flushResponse(`{"ok": "resetting repos"}`, w)
  307. resetRepositories()
  308. go restart()
  309. }
  310. func restPostShutdown(w http.ResponseWriter, r *http.Request) {
  311. flushResponse(`{"ok": "shutting down"}`, w)
  312. go shutdown()
  313. }
  314. func flushResponse(s string, w http.ResponseWriter) {
  315. w.Write([]byte(s + "\n"))
  316. f := w.(http.Flusher)
  317. f.Flush()
  318. }
  319. var cpuUsagePercent [10]float64 // The last ten seconds
  320. var cpuUsageLock sync.RWMutex
  321. func restGetSystem(w http.ResponseWriter, r *http.Request) {
  322. var m runtime.MemStats
  323. runtime.ReadMemStats(&m)
  324. res := make(map[string]interface{})
  325. res["myID"] = myID.String()
  326. res["goroutines"] = runtime.NumGoroutine()
  327. res["alloc"] = m.Alloc
  328. res["sys"] = m.Sys
  329. res["tilde"] = expandTilde("~")
  330. if cfg.Options.GlobalAnnEnabled && discoverer != nil {
  331. res["extAnnounceOK"] = discoverer.ExtAnnounceOK()
  332. }
  333. cpuUsageLock.RLock()
  334. var cpusum float64
  335. for _, p := range cpuUsagePercent {
  336. cpusum += p
  337. }
  338. cpuUsageLock.RUnlock()
  339. res["cpuPercent"] = cpusum / 10
  340. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  341. json.NewEncoder(w).Encode(res)
  342. }
  343. func restGetErrors(w http.ResponseWriter, r *http.Request) {
  344. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  345. guiErrorsMut.Lock()
  346. json.NewEncoder(w).Encode(guiErrors)
  347. guiErrorsMut.Unlock()
  348. }
  349. func restPostError(w http.ResponseWriter, r *http.Request) {
  350. bs, _ := ioutil.ReadAll(r.Body)
  351. r.Body.Close()
  352. showGuiError(0, string(bs))
  353. }
  354. func restClearErrors(w http.ResponseWriter, r *http.Request) {
  355. guiErrorsMut.Lock()
  356. guiErrors = []guiError{}
  357. guiErrorsMut.Unlock()
  358. }
  359. func showGuiError(l logger.LogLevel, err string) {
  360. guiErrorsMut.Lock()
  361. guiErrors = append(guiErrors, guiError{time.Now(), err})
  362. if len(guiErrors) > 5 {
  363. guiErrors = guiErrors[len(guiErrors)-5:]
  364. }
  365. guiErrorsMut.Unlock()
  366. }
  367. func restPostDiscoveryHint(w http.ResponseWriter, r *http.Request) {
  368. var qs = r.URL.Query()
  369. var node = qs.Get("node")
  370. var addr = qs.Get("addr")
  371. if len(node) != 0 && len(addr) != 0 && discoverer != nil {
  372. discoverer.Hint(node, []string{addr})
  373. }
  374. }
  375. func restGetDiscovery(w http.ResponseWriter, r *http.Request) {
  376. json.NewEncoder(w).Encode(discoverer.All())
  377. }
  378. func restGetReport(m *model.Model, w http.ResponseWriter, r *http.Request) {
  379. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  380. json.NewEncoder(w).Encode(reportData(m))
  381. }
  382. func restGetEvents(w http.ResponseWriter, r *http.Request) {
  383. qs := r.URL.Query()
  384. sinceStr := qs.Get("since")
  385. limitStr := qs.Get("limit")
  386. since, _ := strconv.Atoi(sinceStr)
  387. limit, _ := strconv.Atoi(limitStr)
  388. evs := eventSub.Since(since, nil)
  389. if 0 < limit && limit < len(evs) {
  390. evs = evs[len(evs)-limit:]
  391. }
  392. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  393. json.NewEncoder(w).Encode(evs)
  394. }
  395. func restGetUpgrade(w http.ResponseWriter, r *http.Request) {
  396. rel, err := upgrade.LatestRelease(strings.Contains(Version, "-beta"))
  397. if err != nil {
  398. http.Error(w, err.Error(), 500)
  399. return
  400. }
  401. res := make(map[string]interface{})
  402. res["running"] = Version
  403. res["latest"] = rel.Tag
  404. res["newer"] = upgrade.CompareVersions(rel.Tag, Version) == 1
  405. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  406. json.NewEncoder(w).Encode(res)
  407. }
  408. func restGetNodeID(w http.ResponseWriter, r *http.Request) {
  409. qs := r.URL.Query()
  410. idStr := qs.Get("id")
  411. id, err := protocol.NodeIDFromString(idStr)
  412. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  413. if err == nil {
  414. json.NewEncoder(w).Encode(map[string]string{
  415. "id": id.String(),
  416. })
  417. } else {
  418. json.NewEncoder(w).Encode(map[string]string{
  419. "error": err.Error(),
  420. })
  421. }
  422. }
  423. func restGetLang(w http.ResponseWriter, r *http.Request) {
  424. lang := r.Header.Get("Accept-Language")
  425. var langs []string
  426. for _, l := range strings.Split(lang, ",") {
  427. if len(l) >= 2 {
  428. langs = append(langs, l[:2])
  429. }
  430. }
  431. json.NewEncoder(w).Encode(langs)
  432. }
  433. func restPostUpgrade(w http.ResponseWriter, r *http.Request) {
  434. rel, err := upgrade.LatestRelease(strings.Contains(Version, "-beta"))
  435. if err != nil {
  436. l.Warnln(err)
  437. http.Error(w, err.Error(), 500)
  438. return
  439. }
  440. if upgrade.CompareVersions(rel.Tag, Version) == 1 {
  441. err = upgrade.UpgradeTo(rel)
  442. if err != nil {
  443. l.Warnln(err)
  444. http.Error(w, err.Error(), 500)
  445. return
  446. }
  447. restPostRestart(w, r)
  448. }
  449. }
  450. func getQR(w http.ResponseWriter, r *http.Request) {
  451. var qs = r.URL.Query()
  452. var text = qs.Get("text")
  453. code, err := qr.Encode(text, qr.M)
  454. if err != nil {
  455. http.Error(w, "Invalid", 500)
  456. return
  457. }
  458. w.Header().Set("Content-Type", "image/png")
  459. w.Write(code.PNG())
  460. }
  461. func restGetPeerCompletion(m *model.Model, w http.ResponseWriter, r *http.Request) {
  462. tot := map[string]float64{}
  463. count := map[string]float64{}
  464. for _, repo := range cfg.Repositories {
  465. for _, node := range repo.NodeIDs() {
  466. nodeStr := node.String()
  467. if m.ConnectedTo(node) {
  468. tot[nodeStr] += m.Completion(node, repo.ID)
  469. } else {
  470. tot[nodeStr] = 0
  471. }
  472. count[nodeStr]++
  473. }
  474. }
  475. comp := map[string]int{}
  476. for node := range tot {
  477. comp[node] = int(tot[node] / count[node])
  478. }
  479. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  480. json.NewEncoder(w).Encode(comp)
  481. }
  482. func basicAuthMiddleware(username string, passhash string, next http.Handler) http.Handler {
  483. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  484. if validAPIKey(r.Header.Get("X-API-Key")) {
  485. next.ServeHTTP(w, r)
  486. return
  487. }
  488. error := func() {
  489. time.Sleep(time.Duration(rand.Intn(100)+100) * time.Millisecond)
  490. w.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
  491. http.Error(w, "Not Authorized", http.StatusUnauthorized)
  492. }
  493. hdr := r.Header.Get("Authorization")
  494. if !strings.HasPrefix(hdr, "Basic ") {
  495. error()
  496. return
  497. }
  498. hdr = hdr[6:]
  499. bs, err := base64.StdEncoding.DecodeString(hdr)
  500. if err != nil {
  501. error()
  502. return
  503. }
  504. fields := bytes.SplitN(bs, []byte(":"), 2)
  505. if len(fields) != 2 {
  506. error()
  507. return
  508. }
  509. if string(fields[0]) != username {
  510. error()
  511. return
  512. }
  513. if err := bcrypt.CompareHashAndPassword([]byte(passhash), fields[1]); err != nil {
  514. error()
  515. return
  516. }
  517. next.ServeHTTP(w, r)
  518. })
  519. }
  520. func validAPIKey(k string) bool {
  521. return len(apiKey) > 0 && k == apiKey
  522. }
  523. func embeddedStatic(assetDir string) http.Handler {
  524. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  525. file := r.URL.Path
  526. if file[0] == '/' {
  527. file = file[1:]
  528. }
  529. if len(file) == 0 {
  530. file = "index.html"
  531. }
  532. if assetDir != "" {
  533. p := filepath.Join(assetDir, filepath.FromSlash(file))
  534. _, err := os.Stat(p)
  535. if err == nil {
  536. http.ServeFile(w, r, p)
  537. return
  538. }
  539. }
  540. bs, ok := auto.Assets[file]
  541. if !ok {
  542. http.NotFound(w, r)
  543. return
  544. }
  545. mtype := mime.TypeByExtension(filepath.Ext(r.URL.Path))
  546. if len(mtype) != 0 {
  547. w.Header().Set("Content-Type", mtype)
  548. }
  549. w.Header().Set("Content-Length", fmt.Sprintf("%d", len(bs)))
  550. w.Header().Set("Last-Modified", modt)
  551. w.Write(bs)
  552. })
  553. }