gui.go 18 KB

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