From 66cac0a23e0aa237d8f4630de5aab3b83d358d89 Mon Sep 17 00:00:00 2001
From: Thomas Schwery <thomas@inf3.ch>
Date: Thu, 2 Mar 2017 10:37:00 +0100
Subject: [PATCH] Add httpcache to respect the caching headers in the ESI
 responses

---
 .gitignore |  1 +
 main.go    | 31 +++++++++++++++++++++++++++----
 2 files changed, 28 insertions(+), 4 deletions(-)

diff --git a/.gitignore b/.gitignore
index d31efe0..5b68477 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,6 +16,7 @@ vendor/
 *.log
 cache.db
 configuration.toml
+cache.ldb
 
 swagger_linux_amd64
 eve-goclient
diff --git a/main.go b/main.go
index 2ef0f08..2381d44 100644
--- a/main.go
+++ b/main.go
@@ -1,6 +1,7 @@
 package main
 
 import (
+	"crypto/tls"
 	"encoding/json"
 	"sort"
 	"time"
@@ -20,6 +21,8 @@ import (
 
 	"github.com/BurntSushi/toml"
 	"github.com/go-openapi/strfmt"
+	"github.com/gregjones/httpcache"
+	"github.com/gregjones/httpcache/leveldbcache"
 	"github.com/leekchan/accounting"
 	"github.com/logrusorgru/aurora"
 
@@ -74,8 +77,9 @@ var (
 
 	defaultDateFormat = "_2 Jan 2006, 15:04"
 
-	cfgFilePath = flag.String("config", "configuration.toml", "Path to the configuration file.")
-	cacheDBPath = flag.String("cache", "cache.db", "Path to the cache sqlite database.")
+	cfgFilePath  = flag.String("config", "configuration.toml", "Path to the configuration file.")
+	cacheDBPath  = flag.String("cache", "cache.db", "Path to the cache sqlite database.")
+	insecureFlag = flag.Bool("insecure", false, "Do not check the HTTPS certificate")
 )
 
 var ctx = context.Background()
@@ -105,12 +109,31 @@ func main() {
 		cToken = getNewAuthorizationToken()
 	}
 
-	client := googleOauthConfig.Client(oauth2.NoContext, cToken)
+	ldb, ldbErr := leveldbcache.New("cache.ldb")
+	if ldbErr != nil {
+		fmt.Println("Unable to initialize the LevelDB cache.")
+		log.Fatal(ldbErr)
+	}
+	cachingTransport := httpcache.NewTransport(ldb)
+
+	if *insecureFlag {
+		proxiedTransport := &http.Transport{
+			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
+			Proxy:           http.ProxyFromEnvironment,
+		}
+		cachingTransport.Transport = proxiedTransport
+	}
+
+	cachingClient := &http.Client{Transport: cachingTransport}
+
+	ctx := context.WithValue(context.TODO(), oauth2.HTTPClient, cachingClient)
+	client := googleOauthConfig.Client(ctx, cToken)
 
 	m, err := getCharacterInfo(client)
 	if err != nil {
+		log.Println(err)
 		cToken = getNewAuthorizationToken()
-		client = googleOauthConfig.Client(oauth2.NoContext, cToken)
+		client = googleOauthConfig.Client(ctx, cToken)
 		m, err = getCharacterInfo(client)
 		if err != nil {
 			log.Fatal(err)