Last active
October 26, 2015 04:39
-
-
Save mattn/f07cba30529f96e599e6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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