You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
stacosys/go-http/httpfastcache.go

88 lines
1.7 KiB
Go

package main
import (
7 years ago
"encoding/json"
"flag"
"fmt"
"github.com/patrickmn/go-cache"
"io/ioutil"
"log"
"net/http"
7 years ago
"os"
"time"
)
7 years ago
// ConfigType represents config info
type ConfigType struct {
HostPort string
Stacosys string
CorsOrigin string
}
7 years ago
var config ConfigType
var countCache = cache.New(5*time.Minute, 10*time.Minute)
7 years ago
func die(format string, v ...interface{}) {
fmt.Fprintln(os.Stderr, fmt.Sprintf(format, v...))
os.Exit(1)
}
func commentsCount(w http.ResponseWriter, r *http.Request) {
// only GET method is supported
if r.Method != "GET" {
http.NotFound(w, r)
return
}
// set header
w.Header().Add("Content-Type", "application/json")
7 years ago
w.Header().Add("Access-Control-Allow-Origin", config.CorsOrigin)
// get cached value
cachedBody, found := countCache.Get(r.URL.String())
if found {
//log.Printf("return cached value")
w.Write([]byte(cachedBody.(string)))
return
}
// relay request to stacosys
7 years ago
response, err := http.Get(config.Stacosys + r.URL.String())
if err != nil {
http.NotFound(w, r)
return
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
http.NotFound(w, r)
return
}
// cache body and return response
countCache.Set(r.URL.String(), string(body), cache.DefaultExpiration)
log.Printf(string(body))
w.Write(body)
}
func main() {
7 years ago
pathname := flag.String("config", "", "config pathname")
flag.Parse()
if *pathname == "" {
die("%s --config <pathname>", os.Args[0])
}
// read config File
file, e := ioutil.ReadFile(*pathname)
if e != nil {
die("File error: %v", e)
}
fmt.Printf("config: %s\n", string(file))
config := ConfigType{}
json.Unmarshal(file, &config)
http.HandleFunc("/comments/count", commentsCount)
7 years ago
http.ListenAndServe(config.HostPort, nil)
}