day6 模板

master
独孤伶俜 2022-12-01 16:54:42 +08:00
parent 83f283d668
commit 414b1b84d9
5 changed files with 113 additions and 6 deletions

View File

@ -12,11 +12,11 @@ type IssuesSearchResult struct {
}
type Issue struct {
Number int
HTMLURL string `json:"html_url"`
Title string
State string
*User
Number int
HTMLURL string `json:"html_url"`
Title string
State string
User *User
CreatedAt time.Time `json:"created_at"`
Body string // in Markdown format
}

View File

@ -23,7 +23,7 @@ var ConcerError error
func main() {
http.HandleFunc("/", surface)
log.Fatal(http.ListenAndServe("localhost:8080", nil))
log.Fatal(http.ListenAndServe("0.0.0.0:8989", nil))
}
func surface(w http.ResponseWriter, r *http.Request) {

View File

@ -0,0 +1,39 @@
package main
import (
"Study/pkg/github"
"log"
"os"
"text/template"
"time"
)
const temple = `{{.TotalCount}} issues:
{{range .Items}}----------------------------------------
Number: {{.Number}}
User: {{.User.Login}}
Title: {{.Title | printf "%.64s"}}
Age: {{.CreatedAt | daysAgo}} days
{{end}}`
func dayAgo(t time.Time) float64 {
return time.Since(t).Hours() / 24.0
}
func main() {
report, err := template.New("report").
Funcs(template.FuncMap{"daysAgo": dayAgo}).
Parse(temple)
if err != nil {
log.Fatal(err)
}
res, err := github.SearchIssues([]string{"go/golang"})
if err != nil {
log.Fatal(err)
}
//if err := report.ExecuteTemplate(os.Stdout, "temple", res); err != nil {
if err := report.Execute(os.Stdout, res); err != nil {
log.Fatal(err)
}
}

View File

@ -0,0 +1,40 @@
package main
import (
"Study/pkg/github"
"html/template"
"log"
"os"
)
var IssueList = template.Must(template.New("issuelist").Parse(`
<h1>{{.TotalCount}} issues</h1>
<table>
<tr style='text-align: left'>
<th>#</th>
<th>State</th>
<th>User</th>
<th>Title</th>
</tr>
{{range .Items}}
<tr>
<td><a href='{{.HTMLURL}}'>{{.Number}}</a></td>
<td>{{.State}}</td>
<td><a href='{{.User.HTMLURL}}'>{{.User.Login}}</a></td>
<td><a href='{{.HTMLURL}}'>{{.Title}}</a></td>
</tr>
{{end}}
</table>
`))
func main() {
res, err := github.SearchIssues([]string{"repo:golang/go", "3133", "10535"})
if err != nil {
log.Fatal(err)
}
//if err := report.ExecuteTemplate(os.Stdout, "temple", res); err != nil {
if err := IssueList.Execute(os.Stdout, res); err != nil {
log.Fatal(err)
}
}

View File

@ -0,0 +1,28 @@
package main
import (
"html/template"
"log"
"net/http"
)
const templ = `<p>A:{{.A}}</p> <p>B: {{.B}}</p>`
var data struct {
A string
B template.HTML
}
func main() {
http.HandleFunc("/", handle)
log.Fatal(http.ListenAndServe("0.0.0.0:8989", nil))
}
func handle(w http.ResponseWriter, r *http.Request) {
t := template.Must(template.New("escape").Parse(templ))
data.A = "<b>Hello!</b>"
data.B = "<b>Hello!</b>"
if err := t.Execute(w, data); err != nil {
log.Fatal(err)
}
}