Created
January 8, 2015 19:17
-
-
Save damirazo/380a1e4c99946c46a6e7 to your computer and use it in GitHub Desktop.
Структура для загрузки и хранения информации о web странице на go
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
// Ошибки | |
var pageLoadError = errors.New("Произошла ошибка при загрузке страницы") | |
var pageReadError = errors.New("Произошла ошибка при чтении страницы") | |
// Структура для хранения информации о url странице | |
type Page struct { | |
url string | |
response *http.Response | |
body []byte | |
content string | |
isLoaded bool | |
} | |
// Загрузка страницы по указанной ссылке | |
func (self *Page) load(link string) error { | |
self.url = link | |
response, err := http.Get(link) | |
if err != nil { | |
return pageLoadError | |
} | |
self.response = response | |
body, err := ioutil.ReadAll(response.Body) | |
if err != nil { | |
return pageReadError | |
} | |
self.body = body | |
self.content = string(body) | |
self.isLoaded = true | |
return nil | |
} | |
// Закрываем все открытые дескрипторы | |
func (self *Page) close() { | |
if self.isLoaded { | |
self.response.Body.Close() | |
} | |
} | |
// Пример использования: | |
// page := new(Page) | |
// err := page.load("http://google.com") | |
// if err == nil { | |
// println(page.response.StatusCode) | |
// } | |
// page.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment