main.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. // Copyright (C) 2015 Audrius Butkevicius and Contributors (see the CONTRIBUTORS file).
  2. //go:generate go run ../../script/genassets.go gui >auto/gui.go
  3. package main
  4. import (
  5. "bytes"
  6. "compress/gzip"
  7. "crypto/tls"
  8. "encoding/json"
  9. "flag"
  10. "fmt"
  11. "io/ioutil"
  12. "log"
  13. "mime"
  14. "net"
  15. "net/http"
  16. "net/url"
  17. "os"
  18. "path/filepath"
  19. "strconv"
  20. "strings"
  21. "time"
  22. "github.com/golang/groupcache/lru"
  23. "github.com/oschwald/geoip2-golang"
  24. "github.com/prometheus/client_golang/prometheus"
  25. "github.com/prometheus/client_golang/prometheus/promhttp"
  26. "github.com/syncthing/syncthing/cmd/strelaypoolsrv/auto"
  27. "github.com/syncthing/syncthing/lib/rand"
  28. "github.com/syncthing/syncthing/lib/relay/client"
  29. "github.com/syncthing/syncthing/lib/sync"
  30. "github.com/syncthing/syncthing/lib/tlsutil"
  31. "golang.org/x/time/rate"
  32. )
  33. type location struct {
  34. Latitude float64 `json:"latitude"`
  35. Longitude float64 `json:"longitude"`
  36. City string `json:"city"`
  37. Country string `json:"country"`
  38. Continent string `json:"continent"`
  39. }
  40. type relay struct {
  41. URL string `json:"url"`
  42. Location location `json:"location"`
  43. uri *url.URL
  44. Stats *stats `json:"stats"`
  45. StatsRetrieved time.Time `json:"statsRetrieved"`
  46. }
  47. type stats struct {
  48. StartTime time.Time `json:"startTime"`
  49. UptimeSeconds int `json:"uptimeSeconds"`
  50. PendingSessionKeys int `json:"numPendingSessionKeys"`
  51. ActiveSessions int `json:"numActiveSessions"`
  52. Connections int `json:"numConnections"`
  53. Proxies int `json:"numProxies"`
  54. BytesProxied int `json:"bytesProxied"`
  55. GoVersion string `json:"goVersion"`
  56. GoOS string `json:"goOS"`
  57. GoArch string `json:"goArch"`
  58. GoMaxProcs int `json:"goMaxProcs"`
  59. GoRoutines int `json:"goNumRoutine"`
  60. Rates []int64 `json:"kbps10s1m5m15m30m60m"`
  61. Options struct {
  62. NetworkTimeout int `json:"network-timeout"`
  63. PintInterval int `json:"ping-interval"`
  64. MessageTimeout int `json:"message-timeout"`
  65. SessionRate int `json:"per-session-rate"`
  66. GlobalRate int `json:"global-rate"`
  67. Pools []string `json:"pools"`
  68. ProvidedBy string `json:"provided-by"`
  69. } `json:"options"`
  70. }
  71. func (r relay) String() string {
  72. return r.URL
  73. }
  74. type request struct {
  75. relay *relay
  76. result chan result
  77. queueTimer *prometheus.Timer
  78. }
  79. type result struct {
  80. err error
  81. eviction time.Duration
  82. }
  83. var (
  84. testCert tls.Certificate
  85. knownRelaysFile = filepath.Join(os.TempDir(), "strelaypoolsrv_known_relays")
  86. listen = ":80"
  87. dir string
  88. evictionTime = time.Hour
  89. debug bool
  90. getLRUSize = 10 << 10
  91. getLimitBurst = 10
  92. getLimitAvg = 2
  93. postLRUSize = 1 << 10
  94. postLimitBurst = 2
  95. postLimitAvg = 2
  96. getLimit time.Duration
  97. postLimit time.Duration
  98. permRelaysFile string
  99. ipHeader string
  100. geoipPath string
  101. proto string
  102. statsRefresh = time.Minute / 2
  103. getMut = sync.NewRWMutex()
  104. getLRUCache *lru.Cache
  105. postMut = sync.NewRWMutex()
  106. postLRUCache *lru.Cache
  107. requests = make(chan request, 10)
  108. mut = sync.NewRWMutex()
  109. knownRelays = make([]*relay, 0)
  110. permanentRelays = make([]*relay, 0)
  111. evictionTimers = make(map[string]*time.Timer)
  112. )
  113. const (
  114. httpStatusEnhanceYourCalm = 429
  115. )
  116. func main() {
  117. flag.StringVar(&listen, "listen", listen, "Listen address")
  118. flag.StringVar(&dir, "keys", dir, "Directory where http-cert.pem and http-key.pem is stored for TLS listening")
  119. flag.BoolVar(&debug, "debug", debug, "Enable debug output")
  120. flag.DurationVar(&evictionTime, "eviction", evictionTime, "After how long the relay is evicted")
  121. flag.IntVar(&getLRUSize, "get-limit-cache", getLRUSize, "Get request limiter cache size")
  122. flag.IntVar(&getLimitAvg, "get-limit-avg", getLimitAvg, "Allowed average get request rate, per 10 s")
  123. flag.IntVar(&getLimitBurst, "get-limit-burst", getLimitBurst, "Allowed burst get requests")
  124. flag.IntVar(&postLRUSize, "post-limit-cache", postLRUSize, "Post request limiter cache size")
  125. flag.IntVar(&postLimitAvg, "post-limit-avg", postLimitAvg, "Allowed average post request rate, per minute")
  126. flag.IntVar(&postLimitBurst, "post-limit-burst", postLimitBurst, "Allowed burst post requests")
  127. flag.StringVar(&permRelaysFile, "perm-relays", "", "Path to list of permanent relays")
  128. flag.StringVar(&ipHeader, "ip-header", "", "Name of header which holds clients ip:port. Only meaningful when running behind a reverse proxy.")
  129. flag.StringVar(&geoipPath, "geoip", "GeoLite2-City.mmdb", "Path to GeoLite2-City database")
  130. flag.StringVar(&proto, "protocol", "tcp", "Protocol used for listening. 'tcp' for IPv4 and IPv6, 'tcp4' for IPv4, 'tcp6' for IPv6")
  131. flag.DurationVar(&statsRefresh, "stats-refresh", statsRefresh, "Interval at which to refresh relay stats")
  132. flag.Parse()
  133. getLimit = 10 * time.Second / time.Duration(getLimitAvg)
  134. postLimit = time.Minute / time.Duration(postLimitAvg)
  135. getLRUCache = lru.New(getLRUSize)
  136. postLRUCache = lru.New(postLRUSize)
  137. var listener net.Listener
  138. var err error
  139. if permRelaysFile != "" {
  140. permanentRelays = loadRelays(permRelaysFile)
  141. }
  142. testCert = createTestCertificate()
  143. go requestProcessor()
  144. // Load relays from cache in the background.
  145. // Load them in a serial fashion to make sure any genuine requests
  146. // are not dropped.
  147. go func() {
  148. for _, relay := range loadRelays(knownRelaysFile) {
  149. resultChan := make(chan result)
  150. requests <- request{relay, resultChan, nil}
  151. result := <-resultChan
  152. if result.err != nil {
  153. relayTestsTotal.WithLabelValues("failed").Inc()
  154. } else {
  155. relayTestsTotal.WithLabelValues("success").Inc()
  156. }
  157. }
  158. // Run the the stats refresher once the relays are loaded.
  159. statsRefresher(statsRefresh)
  160. }()
  161. if dir != "" {
  162. if debug {
  163. log.Println("Starting TLS listener on", listen)
  164. }
  165. certFile, keyFile := filepath.Join(dir, "http-cert.pem"), filepath.Join(dir, "http-key.pem")
  166. var cert tls.Certificate
  167. cert, err = tls.LoadX509KeyPair(certFile, keyFile)
  168. if err != nil {
  169. log.Fatalln("Failed to load HTTP X509 key pair:", err)
  170. }
  171. tlsCfg := &tls.Config{
  172. Certificates: []tls.Certificate{cert},
  173. MinVersion: tls.VersionTLS10, // No SSLv3
  174. CipherSuites: []uint16{
  175. // No RC4
  176. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  177. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  178. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  179. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  180. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  181. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  182. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  183. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  184. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  185. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  186. },
  187. }
  188. listener, err = tls.Listen(proto, listen, tlsCfg)
  189. } else {
  190. if debug {
  191. log.Println("Starting plain listener on", listen)
  192. }
  193. listener, err = net.Listen(proto, listen)
  194. }
  195. if err != nil {
  196. log.Fatalln("listen:", err)
  197. }
  198. handler := http.NewServeMux()
  199. handler.HandleFunc("/", handleAssets)
  200. handler.HandleFunc("/endpoint", handleRequest)
  201. handler.HandleFunc("/metrics", handleMetrics)
  202. srv := http.Server{
  203. Handler: handler,
  204. ReadTimeout: 10 * time.Second,
  205. }
  206. err = srv.Serve(listener)
  207. if err != nil {
  208. log.Fatalln("serve:", err)
  209. }
  210. }
  211. func handleMetrics(w http.ResponseWriter, r *http.Request) {
  212. timer := prometheus.NewTimer(metricsRequestsSeconds)
  213. // Acquire the mutex just to make sure we're not caught mid-way stats collection
  214. mut.RLock()
  215. promhttp.Handler().ServeHTTP(w, r)
  216. mut.RUnlock()
  217. timer.ObserveDuration()
  218. }
  219. func handleAssets(w http.ResponseWriter, r *http.Request) {
  220. w.Header().Set("Cache-Control", "no-cache, must-revalidate")
  221. assets := auto.Assets()
  222. path := r.URL.Path[1:]
  223. if path == "" {
  224. path = "index.html"
  225. }
  226. bs, ok := assets[path]
  227. if !ok {
  228. w.WriteHeader(http.StatusNotFound)
  229. return
  230. }
  231. etag := fmt.Sprintf("%d", auto.Generated)
  232. modified := time.Unix(auto.Generated, 0).UTC()
  233. w.Header().Set("Last-Modified", modified.Format(http.TimeFormat))
  234. w.Header().Set("Etag", etag)
  235. mtype := mimeTypeForFile(path)
  236. if len(mtype) != 0 {
  237. w.Header().Set("Content-Type", mtype)
  238. }
  239. if t, err := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); err == nil && modified.Add(time.Second).After(t) {
  240. w.WriteHeader(http.StatusNotModified)
  241. return
  242. }
  243. if match := r.Header.Get("If-None-Match"); match != "" {
  244. if strings.Contains(match, etag) {
  245. w.WriteHeader(http.StatusNotModified)
  246. return
  247. }
  248. }
  249. if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  250. w.Header().Set("Content-Encoding", "gzip")
  251. } else {
  252. // ungzip if browser not send gzip accepted header
  253. var gr *gzip.Reader
  254. gr, _ = gzip.NewReader(bytes.NewReader(bs))
  255. bs, _ = ioutil.ReadAll(gr)
  256. gr.Close()
  257. }
  258. w.Header().Set("Content-Length", fmt.Sprintf("%d", len(bs)))
  259. w.Write(bs)
  260. }
  261. func mimeTypeForFile(file string) string {
  262. // We use a built in table of the common types since the system
  263. // TypeByExtension might be unreliable. But if we don't know, we delegate
  264. // to the system.
  265. ext := filepath.Ext(file)
  266. switch ext {
  267. case ".htm", ".html":
  268. return "text/html"
  269. case ".css":
  270. return "text/css"
  271. case ".js":
  272. return "application/javascript"
  273. case ".json":
  274. return "application/json"
  275. case ".png":
  276. return "image/png"
  277. case ".ttf":
  278. return "application/x-font-ttf"
  279. case ".woff":
  280. return "application/x-font-woff"
  281. case ".svg":
  282. return "image/svg+xml"
  283. default:
  284. return mime.TypeByExtension(ext)
  285. }
  286. }
  287. func handleRequest(w http.ResponseWriter, r *http.Request) {
  288. timer := prometheus.NewTimer(apiRequestsSeconds.WithLabelValues(r.Method))
  289. lw := NewLoggingResponseWriter(w)
  290. defer func() {
  291. timer.ObserveDuration()
  292. apiRequestsTotal.WithLabelValues(r.Method, strconv.Itoa(lw.statusCode)).Inc()
  293. }()
  294. if ipHeader != "" {
  295. r.RemoteAddr = r.Header.Get(ipHeader)
  296. }
  297. w.Header().Set("Access-Control-Allow-Origin", "*")
  298. switch r.Method {
  299. case "GET":
  300. if limit(r.RemoteAddr, getLRUCache, getMut, getLimit, getLimitBurst) {
  301. w.WriteHeader(httpStatusEnhanceYourCalm)
  302. return
  303. }
  304. handleGetRequest(w, r)
  305. case "POST":
  306. if limit(r.RemoteAddr, postLRUCache, postMut, postLimit, postLimitBurst) {
  307. w.WriteHeader(httpStatusEnhanceYourCalm)
  308. return
  309. }
  310. handlePostRequest(w, r)
  311. default:
  312. if debug {
  313. log.Println("Unhandled HTTP method", r.Method)
  314. }
  315. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  316. }
  317. }
  318. func handleGetRequest(w http.ResponseWriter, r *http.Request) {
  319. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  320. mut.RLock()
  321. relays := append(permanentRelays, knownRelays...)
  322. mut.RUnlock()
  323. // Shuffle
  324. rand.Shuffle(relays)
  325. json.NewEncoder(w).Encode(map[string][]*relay{
  326. "relays": relays,
  327. })
  328. }
  329. func handlePostRequest(w http.ResponseWriter, r *http.Request) {
  330. var newRelay relay
  331. err := json.NewDecoder(r.Body).Decode(&newRelay)
  332. r.Body.Close()
  333. if err != nil {
  334. if debug {
  335. log.Println("Failed to parse payload")
  336. }
  337. http.Error(w, err.Error(), 500)
  338. return
  339. }
  340. uri, err := url.Parse(newRelay.URL)
  341. if err != nil {
  342. if debug {
  343. log.Println("Failed to parse URI", newRelay.URL)
  344. }
  345. http.Error(w, err.Error(), 500)
  346. return
  347. }
  348. host, port, err := net.SplitHostPort(uri.Host)
  349. if err != nil {
  350. if debug {
  351. log.Println("Failed to split URI", newRelay.URL)
  352. }
  353. http.Error(w, err.Error(), 500)
  354. return
  355. }
  356. // Get the IP address of the client
  357. rhost := r.RemoteAddr
  358. if host, _, err := net.SplitHostPort(rhost); err == nil {
  359. rhost = host
  360. }
  361. ip := net.ParseIP(host)
  362. // The client did not provide an IP address, use the IP address of the client.
  363. if ip == nil || ip.IsUnspecified() {
  364. uri.Host = net.JoinHostPort(rhost, port)
  365. newRelay.URL = uri.String()
  366. } else if host != rhost {
  367. if debug {
  368. log.Println("IP address advertised does not match client IP address", r.RemoteAddr, uri)
  369. }
  370. http.Error(w, fmt.Sprintf("IP advertised %s does not match client IP %s", host, rhost), http.StatusUnauthorized)
  371. return
  372. }
  373. newRelay.uri = uri
  374. for _, current := range permanentRelays {
  375. if current.uri.Host == newRelay.uri.Host {
  376. if debug {
  377. log.Println("Asked to add a relay", newRelay, "which exists in permanent list")
  378. }
  379. http.Error(w, "Invalid request", http.StatusBadRequest)
  380. return
  381. }
  382. }
  383. reschan := make(chan result)
  384. select {
  385. case requests <- request{&newRelay, reschan, prometheus.NewTimer(relayTestActionsSeconds.WithLabelValues("queue"))}:
  386. result := <-reschan
  387. if result.err != nil {
  388. relayTestsTotal.WithLabelValues("failed").Inc()
  389. http.Error(w, result.err.Error(), http.StatusBadRequest)
  390. return
  391. }
  392. relayTestsTotal.WithLabelValues("success").Inc()
  393. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  394. json.NewEncoder(w).Encode(map[string]time.Duration{
  395. "evictionIn": result.eviction,
  396. })
  397. default:
  398. relayTestsTotal.WithLabelValues("dropped").Inc()
  399. if debug {
  400. log.Println("Dropping request")
  401. }
  402. w.WriteHeader(httpStatusEnhanceYourCalm)
  403. }
  404. }
  405. func requestProcessor() {
  406. for request := range requests {
  407. if request.queueTimer != nil {
  408. request.queueTimer.ObserveDuration()
  409. }
  410. timer := prometheus.NewTimer(relayTestActionsSeconds.WithLabelValues("test"))
  411. handleRelayTest(request)
  412. timer.ObserveDuration()
  413. }
  414. }
  415. func handleRelayTest(request request) {
  416. if debug {
  417. log.Println("Request for", request.relay)
  418. }
  419. if !client.TestRelay(request.relay.uri, []tls.Certificate{testCert}, time.Second, 2*time.Second, 3) {
  420. if debug {
  421. log.Println("Test for relay", request.relay, "failed")
  422. }
  423. request.result <- result{fmt.Errorf("connection test failed"), 0}
  424. return
  425. }
  426. stats := fetchStats(request.relay)
  427. location := getLocation(request.relay.uri.Host)
  428. mut.Lock()
  429. if stats != nil {
  430. updateMetrics(request.relay.uri.Host, *stats, location)
  431. }
  432. request.relay.Stats = stats
  433. request.relay.StatsRetrieved = time.Now()
  434. request.relay.Location = location
  435. timer, ok := evictionTimers[request.relay.uri.Host]
  436. if ok {
  437. if debug {
  438. log.Println("Stopping existing timer for", request.relay)
  439. }
  440. timer.Stop()
  441. }
  442. for i, current := range knownRelays {
  443. if current.uri.Host == request.relay.uri.Host {
  444. if debug {
  445. log.Println("Relay", request.relay, "already exists")
  446. }
  447. // Evict the old entry anyway, as configuration might have changed.
  448. last := len(knownRelays) - 1
  449. knownRelays[i] = knownRelays[last]
  450. knownRelays = knownRelays[:last]
  451. goto found
  452. }
  453. }
  454. if debug {
  455. log.Println("Adding new relay", request.relay)
  456. }
  457. found:
  458. knownRelays = append(knownRelays, request.relay)
  459. evictionTimers[request.relay.uri.Host] = time.AfterFunc(evictionTime, evict(request.relay))
  460. mut.Unlock()
  461. if err := saveRelays(knownRelaysFile, knownRelays); err != nil {
  462. log.Println("Failed to write known relays: " + err.Error())
  463. }
  464. request.result <- result{nil, evictionTime}
  465. }
  466. func evict(relay *relay) func() {
  467. return func() {
  468. mut.Lock()
  469. defer mut.Unlock()
  470. if debug {
  471. log.Println("Evicting", relay)
  472. }
  473. for i, current := range knownRelays {
  474. if current.uri.Host == relay.uri.Host {
  475. if debug {
  476. log.Println("Evicted", relay)
  477. }
  478. last := len(knownRelays) - 1
  479. knownRelays[i] = knownRelays[last]
  480. knownRelays = knownRelays[:last]
  481. deleteMetrics(current.uri.Host)
  482. }
  483. }
  484. delete(evictionTimers, relay.uri.Host)
  485. }
  486. }
  487. func limit(addr string, cache *lru.Cache, lock sync.RWMutex, intv time.Duration, burst int) bool {
  488. if host, _, err := net.SplitHostPort(addr); err == nil {
  489. addr = host
  490. }
  491. lock.RLock()
  492. bkt, ok := cache.Get(addr)
  493. lock.RUnlock()
  494. if ok {
  495. bkt := bkt.(*rate.Limiter)
  496. if !bkt.Allow() {
  497. // Rate limit
  498. return true
  499. }
  500. } else {
  501. lock.Lock()
  502. cache.Add(addr, rate.NewLimiter(rate.Every(intv), burst))
  503. lock.Unlock()
  504. }
  505. return false
  506. }
  507. func loadRelays(file string) []*relay {
  508. content, err := ioutil.ReadFile(file)
  509. if err != nil {
  510. log.Println("Failed to load relays: " + err.Error())
  511. return nil
  512. }
  513. var relays []*relay
  514. for _, line := range strings.Split(string(content), "\n") {
  515. if len(line) == 0 {
  516. continue
  517. }
  518. uri, err := url.Parse(line)
  519. if err != nil {
  520. if debug {
  521. log.Println("Skipping relay", line, "due to parse error", err)
  522. }
  523. continue
  524. }
  525. relays = append(relays, &relay{
  526. URL: line,
  527. Location: getLocation(uri.Host),
  528. uri: uri,
  529. })
  530. if debug {
  531. log.Println("Adding relay", line)
  532. }
  533. }
  534. return relays
  535. }
  536. func saveRelays(file string, relays []*relay) error {
  537. var content string
  538. for _, relay := range relays {
  539. content += relay.uri.String() + "\n"
  540. }
  541. return ioutil.WriteFile(file, []byte(content), 0777)
  542. }
  543. func createTestCertificate() tls.Certificate {
  544. tmpDir, err := ioutil.TempDir("", "relaypoolsrv")
  545. if err != nil {
  546. log.Fatal(err)
  547. }
  548. certFile, keyFile := filepath.Join(tmpDir, "cert.pem"), filepath.Join(tmpDir, "key.pem")
  549. cert, err := tlsutil.NewCertificate(certFile, keyFile, "relaypoolsrv", 20*365)
  550. if err != nil {
  551. log.Fatalln("Failed to create test X509 key pair:", err)
  552. }
  553. return cert
  554. }
  555. func getLocation(host string) location {
  556. timer := prometheus.NewTimer(locationLookupSeconds)
  557. defer timer.ObserveDuration()
  558. db, err := geoip2.Open(geoipPath)
  559. if err != nil {
  560. return location{}
  561. }
  562. defer db.Close()
  563. addr, err := net.ResolveTCPAddr("tcp", host)
  564. if err != nil {
  565. return location{}
  566. }
  567. city, err := db.City(addr.IP)
  568. if err != nil {
  569. return location{}
  570. }
  571. return location{
  572. Longitude: city.Location.Longitude,
  573. Latitude: city.Location.Latitude,
  574. City: city.City.Names["en"],
  575. Country: city.Country.IsoCode,
  576. Continent: city.Continent.Code,
  577. }
  578. }
  579. type loggingResponseWriter struct {
  580. http.ResponseWriter
  581. statusCode int
  582. }
  583. func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
  584. return &loggingResponseWriter{w, http.StatusOK}
  585. }
  586. func (lrw *loggingResponseWriter) WriteHeader(code int) {
  587. lrw.statusCode = code
  588. lrw.ResponseWriter.WriteHeader(code)
  589. }