Skip to content

Commit ecaf702

Browse files
authored
Merge pull request #547 from devlights/add-rss2-example
2 parents 1203489 + cd778bd commit ecaf702

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed

examples/singleapp/rss2/.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
rss2*
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
version: '3'
2+
3+
tasks:
4+
default:
5+
cmds:
6+
- task: run
7+
install-lib:
8+
cmds:
9+
- go install golang.org/x/tools/cmd/goimports@latest
10+
- go install honnef.co/go/tools/cmd/staticcheck@latest
11+
build:
12+
deps: [ install-lib ]
13+
cmds:
14+
- goimports -w .
15+
- go vet
16+
- staticcheck
17+
- go build
18+
run:
19+
deps: [ build ]
20+
cmds:
21+
- ./rss2

examples/singleapp/rss2/main.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package main
2+
3+
import (
4+
"encoding/xml"
5+
"fmt"
6+
"io"
7+
"net/http"
8+
)
9+
10+
type (
11+
Item struct {
12+
XMLName xml.Name `xml:"item"`
13+
Title string `xml:"title"`
14+
}
15+
Rss struct {
16+
XMLName xml.Name `xml:"rss"`
17+
Items []Item `xml:"channel>item"`
18+
}
19+
)
20+
21+
const (
22+
URL = "https://devlights.hatenablog.com/rss"
23+
)
24+
25+
func panicOnErr[T any](v T, err error) T {
26+
if err != nil {
27+
panic(err)
28+
}
29+
30+
return v
31+
}
32+
33+
// ブログ [いろいろ備忘録日記](https://devlights.hatenablog.com/) から RSS 2.0 を取得して表示するサンプルです。
34+
//
35+
// REFERENCES:
36+
// - https://qiita.com/you8/items/e903fd463cf770688e1e
37+
func main() {
38+
fmt.Printf("[URL] %s\n", URL)
39+
40+
resp := panicOnErr(http.Get(URL))
41+
body := panicOnErr(io.ReadAll(resp.Body))
42+
defer resp.Body.Close()
43+
44+
var rss Rss
45+
if err := xml.Unmarshal(body, &rss); err != nil {
46+
panic(err)
47+
}
48+
49+
for i, item := range rss.Items {
50+
fmt.Printf("[%2d] %s\n", i+1, item.Title)
51+
}
52+
}

0 commit comments

Comments
 (0)