main.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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. "math/rand"
  14. "mime"
  15. "net"
  16. "net/http"
  17. "net/url"
  18. "os"
  19. "path/filepath"
  20. "strconv"
  21. "strings"
  22. "time"
  23. "github.com/golang/groupcache/lru"
  24. "github.com/oschwald/geoip2-golang"
  25. "github.com/prometheus/client_golang/prometheus"
  26. "github.com/prometheus/client_golang/prometheus/promhttp"
  27. "github.com/syncthing/syncthing/cmd/strelaypoolsrv/auto"
  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. for i := range relays {
  325. j := rand.Intn(i + 1)
  326. relays[i], relays[j] = relays[j], relays[i]
  327. }
  328. json.NewEncoder(w).Encode(map[string][]*relay{
  329. "relays": relays,
  330. })
  331. }
  332. func handlePostRequest(w http.ResponseWriter, r *http.Request) {
  333. var newRelay relay
  334. err := json.NewDecoder(r.Body).Decode(&newRelay)
  335. r.Body.Close()
  336. if err != nil {
  337. if debug {
  338. log.Println("Failed to parse payload")
  339. }
  340. http.Error(w, err.Error(), 500)
  341. return
  342. }
  343. uri, err := url.Parse(newRelay.URL)
  344. if err != nil {
  345. if debug {
  346. log.Println("Failed to parse URI", newRelay.URL)
  347. }
  348. http.Error(w, err.Error(), 500)
  349. return
  350. }
  351. host, port, err := net.SplitHostPort(uri.Host)
  352. if err != nil {
  353. if debug {
  354. log.Println("Failed to split URI", newRelay.URL)
  355. }
  356. http.Error(w, err.Error(), 500)
  357. return
  358. }
  359. // Get the IP address of the client
  360. rhost := r.RemoteAddr
  361. if host, _, err := net.SplitHostPort(rhost); err == nil {
  362. rhost = host
  363. }
  364. ip := net.ParseIP(host)
  365. // The client did not provide an IP address, use the IP address of the client.
  366. if ip == nil || ip.IsUnspecified() {
  367. uri.Host = net.JoinHostPort(rhost, port)
  368. newRelay.URL = uri.String()
  369. } else if host != rhost {
  370. if debug {
  371. log.Println("IP address advertised does not match client IP address", r.RemoteAddr, uri)
  372. }
  373. http.Error(w, fmt.Sprintf("IP advertised %s does not match client IP %s", host, rhost), http.StatusUnauthorized)
  374. return
  375. }
  376. newRelay.uri = uri
  377. for _, current := range permanentRelays {
  378. if current.uri.Host == newRelay.uri.Host {
  379. if debug {
  380. log.Println("Asked to add a relay", newRelay, "which exists in permanent list")
  381. }
  382. http.Error(w, "Invalid request", http.StatusBadRequest)
  383. return
  384. }
  385. }
  386. reschan := make(chan result)
  387. select {
  388. case requests <- request{&newRelay, reschan, prometheus.NewTimer(relayTestActionsSeconds.WithLabelValues("queue"))}:
  389. result := <-reschan
  390. if result.err != nil {
  391. relayTestsTotal.WithLabelValues("failed").Inc()
  392. http.Error(w, result.err.Error(), http.StatusBadRequest)
  393. return
  394. }
  395. relayTestsTotal.WithLabelValues("success").Inc()
  396. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  397. json.NewEncoder(w).Encode(map[string]time.Duration{
  398. "evictionIn": result.eviction,
  399. })
  400. default:
  401. relayTestsTotal.WithLabelValues("dropped").Inc()
  402. if debug {
  403. log.Println("Dropping request")
  404. }
  405. w.WriteHeader(httpStatusEnhanceYourCalm)
  406. }
  407. }
  408. func requestProcessor() {
  409. for request := range requests {
  410. if request.queueTimer != nil {
  411. request.queueTimer.ObserveDuration()
  412. }
  413. timer := prometheus.NewTimer(relayTestActionsSeconds.WithLabelValues("test"))
  414. handleRelayTest(request)
  415. timer.ObserveDuration()
  416. }
  417. }
  418. func handleRelayTest(request request) {
  419. if debug {
  420. log.Println("Request for", request.relay)
  421. }
  422. if !client.TestRelay(request.relay.uri, []tls.Certificate{testCert}, time.Second, 2*time.Second, 3) {
  423. if debug {
  424. log.Println("Test for relay", request.relay, "failed")
  425. }
  426. request.result <- result{fmt.Errorf("connection test failed"), 0}
  427. return
  428. }
  429. stats := fetchStats(request.relay)
  430. location := getLocation(request.relay.uri.Host)
  431. mut.Lock()
  432. if stats != nil {
  433. updateMetrics(request.relay.uri.Host, *stats, location)
  434. }
  435. request.relay.Stats = stats
  436. request.relay.StatsRetrieved = time.Now()
  437. request.relay.Location = location
  438. timer, ok := evictionTimers[request.relay.uri.Host]
  439. if ok {
  440. if debug {
  441. log.Println("Stopping existing timer for", request.relay)
  442. }
  443. timer.Stop()
  444. }
  445. for i, current := range knownRelays {
  446. if current.uri.Host == request.relay.uri.Host {
  447. if debug {
  448. log.Println("Relay", request.relay, "already exists")
  449. }
  450. // Evict the old entry anyway, as configuration might have changed.
  451. last := len(knownRelays) - 1
  452. knownRelays[i] = knownRelays[last]
  453. knownRelays = knownRelays[:last]
  454. goto found
  455. }
  456. }
  457. if debug {
  458. log.Println("Adding new relay", request.relay)
  459. }
  460. found:
  461. knownRelays = append(knownRelays, request.relay)
  462. evictionTimers[request.relay.uri.Host] = time.AfterFunc(evictionTime, evict(request.relay))
  463. mut.Unlock()
  464. if err := saveRelays(knownRelaysFile, knownRelays); err != nil {
  465. log.Println("Failed to write known relays: " + err.Error())
  466. }
  467. request.result <- result{nil, evictionTime}
  468. }
  469. func evict(relay *relay) func() {
  470. return func() {
  471. mut.Lock()
  472. defer mut.Unlock()
  473. if debug {
  474. log.Println("Evicting", relay)
  475. }
  476. for i, current := range knownRelays {
  477. if current.uri.Host == relay.uri.Host {
  478. if debug {
  479. log.Println("Evicted", relay)
  480. }
  481. last := len(knownRelays) - 1
  482. knownRelays[i] = knownRelays[last]
  483. knownRelays = knownRelays[:last]
  484. deleteMetrics(current.uri.Host)
  485. }
  486. }
  487. delete(evictionTimers, relay.uri.Host)
  488. }
  489. }
  490. func limit(addr string, cache *lru.Cache, lock sync.RWMutex, intv time.Duration, burst int) bool {
  491. if host, _, err := net.SplitHostPort(addr); err == nil {
  492. addr = host
  493. }
  494. lock.RLock()
  495. bkt, ok := cache.Get(addr)
  496. lock.RUnlock()
  497. if ok {
  498. bkt := bkt.(*rate.Limiter)
  499. if !bkt.Allow() {
  500. // Rate limit
  501. return true
  502. }
  503. } else {
  504. lock.Lock()
  505. cache.Add(addr, rate.NewLimiter(rate.Every(intv), burst))
  506. lock.Unlock()
  507. }
  508. return false
  509. }
  510. func loadRelays(file string) []*relay {
  511. content, err := ioutil.ReadFile(file)
  512. if err != nil {
  513. log.Println("Failed to load relays: " + err.Error())
  514. return nil
  515. }
  516. var relays []*relay
  517. for _, line := range strings.Split(string(content), "\n") {
  518. if len(line) == 0 {
  519. continue
  520. }
  521. uri, err := url.Parse(line)
  522. if err != nil {
  523. if debug {
  524. log.Println("Skipping relay", line, "due to parse error", err)
  525. }
  526. continue
  527. }
  528. relays = append(relays, &relay{
  529. URL: line,
  530. Location: getLocation(uri.Host),
  531. uri: uri,
  532. })
  533. if debug {
  534. log.Println("Adding relay", line)
  535. }
  536. }
  537. return relays
  538. }
  539. func saveRelays(file string, relays []*relay) error {
  540. var content string
  541. for _, relay := range relays {
  542. content += relay.uri.String() + "\n"
  543. }
  544. return ioutil.WriteFile(file, []byte(content), 0777)
  545. }
  546. func createTestCertificate() tls.Certificate {
  547. tmpDir, err := ioutil.TempDir("", "relaypoolsrv")
  548. if err != nil {
  549. log.Fatal(err)
  550. }
  551. certFile, keyFile := filepath.Join(tmpDir, "cert.pem"), filepath.Join(tmpDir, "key.pem")
  552. cert, err := tlsutil.NewCertificate(certFile, keyFile, "relaypoolsrv")
  553. if err != nil {
  554. log.Fatalln("Failed to create test X509 key pair:", err)
  555. }
  556. return cert
  557. }
  558. func getLocation(host string) location {
  559. timer := prometheus.NewTimer(locationLookupSeconds)
  560. defer timer.ObserveDuration()
  561. db, err := geoip2.Open(geoipPath)
  562. if err != nil {
  563. return location{}
  564. }
  565. defer db.Close()
  566. addr, err := net.ResolveTCPAddr("tcp", host)
  567. if err != nil {
  568. return location{}
  569. }
  570. city, err := db.City(addr.IP)
  571. if err != nil {
  572. return location{}
  573. }
  574. return location{
  575. Longitude: city.Location.Longitude,
  576. Latitude: city.Location.Latitude,
  577. City: city.City.Names["en"],
  578. Country: city.Country.IsoCode,
  579. Continent: city.Continent.Code,
  580. }
  581. }
  582. type loggingResponseWriter struct {
  583. http.ResponseWriter
  584. statusCode int
  585. }
  586. func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
  587. return &loggingResponseWriter{w, http.StatusOK}
  588. }
  589. func (lrw *loggingResponseWriter) WriteHeader(code int) {
  590. lrw.statusCode = code
  591. lrw.ResponseWriter.WriteHeader(code)
  592. }