1
restaurant-search/webcache.go

80 lines
2.2 KiB
Go
Raw Normal View History

2015-08-13 07:29:39 +00:00
/*
* Copyright (c) 2015 Alex Yatskov <alex@foosoft.net>
* Author: Alex Yatskov <alex@foosoft.net>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package main
import (
"bytes"
"crypto/md5"
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
"github.com/PuerkitoBio/goquery"
)
type webCache struct {
2015-08-13 09:27:25 +00:00
cacheDir string
2015-08-13 07:29:39 +00:00
}
2015-08-13 09:27:25 +00:00
func newWebCache(cacheDir string) (*webCache, error) {
if err := os.MkdirAll(cacheDir, 0755); err != nil {
2015-08-13 07:29:39 +00:00
return nil, err
}
2015-08-13 09:27:25 +00:00
return &webCache{cacheDir: cacheDir}, nil
2015-08-13 07:29:39 +00:00
}
func (c *webCache) urlToLocal(url string) string {
hash := md5.New()
hash.Write([]byte(url))
2015-08-13 09:27:25 +00:00
return path.Join(c.cacheDir, fmt.Sprintf("%x.html", hash.Sum(nil)))
2015-08-13 07:29:39 +00:00
}
2015-08-13 10:18:17 +00:00
func (c *webCache) load(url string) (*goquery.Document, error) {
2015-08-13 07:29:39 +00:00
localPath := c.urlToLocal(url)
if file, err := os.Open(localPath); err == nil {
defer file.Close()
return goquery.NewDocumentFromReader(file)
} else {
res, err := http.Get(url)
if err != nil {
return nil, err
}
defer res.Body.Close()
var buff bytes.Buffer
if _, err := buff.ReadFrom(res.Body); err != nil {
return nil, err
}
if err := ioutil.WriteFile(localPath, buff.Bytes(), 0644); err != nil {
return nil, err
}
return goquery.NewDocumentFromReader(&buff)
}
}