This commit is contained in:
@ -1,9 +1,12 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"github.com/caarlos0/env/v6"
|
||||
"log"
|
||||
"meow.tf/go/cacheinterface"
|
||||
"meow.tf/go/linkinfo"
|
||||
"net"
|
||||
"net/http"
|
||||
@ -12,10 +15,12 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
api *linkinfo.LinkInfoApi
|
||||
api *linkinfo.LinkInfoApi
|
||||
cacheInterface cache.CacheInterface
|
||||
)
|
||||
|
||||
type apiConfig struct {
|
||||
Cache string `env:"CACHE"`
|
||||
LocalAddress string `env:"LOCAL_ADDRESS"`
|
||||
ImgurClientId string `env:"IMGUR_CLIENT_ID"`
|
||||
YoutubeKey string `env:"YOUTUBE_KEY"`
|
||||
@ -57,9 +62,9 @@ func main() {
|
||||
|
||||
api = linkinfo.New(opts...)
|
||||
|
||||
if addr := os.Getenv("LOCAL_ADDRESS"); addr != "" {
|
||||
var err error
|
||||
var err error
|
||||
|
||||
if addr := os.Getenv("LOCAL_ADDRESS"); addr != "" {
|
||||
api.Client, err = constructBoundClient(addr)
|
||||
|
||||
if err != nil {
|
||||
@ -67,6 +72,14 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
if config.Cache != "" {
|
||||
cacheInterface, err = cache.New(config.Cache)
|
||||
|
||||
if err != nil {
|
||||
log.Fatalln("Unable to create cache:", err)
|
||||
}
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/info", handleInfoRequest)
|
||||
http.ListenAndServe(":8080", mux)
|
||||
@ -82,6 +95,19 @@ func handleInfoRequest(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
h := md5.New()
|
||||
key := hex.EncodeToString(h.Sum([]byte(urlStr)))
|
||||
|
||||
if cacheInterface != nil {
|
||||
cached, err := cacheInterface.Get(key)
|
||||
|
||||
if cached != nil && err == nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write(cached)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
ret, err := api.Retrieve(urlStr)
|
||||
|
||||
if err != nil {
|
||||
@ -90,13 +116,19 @@ func handleInfoRequest(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
err = json.NewEncoder(w).Encode(ret)
|
||||
b, err := json.Marshal(ret)
|
||||
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if cacheInterface != nil {
|
||||
cacheInterface.Set(key, b, 10*time.Minute)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write(b)
|
||||
}
|
||||
|
||||
func constructBoundClient(addr string) (*http.Client, error) {
|
||||
|
Reference in New Issue
Block a user