Skip to content

Instantly share code, notes, and snippets.

@mattn
Last active October 26, 2015 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattn/f07cba30529f96e599e6 to your computer and use it in GitHub Desktop.
Save mattn/f07cba30529f96e599e6 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
)
type Page struct {
Title string
Body []byte
}
var normalizer = strings.NewReplacer(
" ", "_",
)
func (p *Page) save() error {
filename := normalizer.Replace(p.Title) + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
func loadPage(title string) (*Page, error) {
filename := normalizer.Replace(title) + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return &Page{Title: title, Body: body}, nil
}
func main() {
res, err := http.Get("http://www.google.com/robots.txt")
if err != nil {
log.Fatal(err)
}
robots, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
}
p1 := &Page{Title: "Google Robots", Body: robots}
p1.save()
p2, _ := loadPage("Google Robots")
fmt.Println(string(p2.Body))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment