Skip to content

Commit

Permalink
更换前端模板
Browse files Browse the repository at this point in the history
  • Loading branch information
icowan committed Feb 13, 2020
1 parent 16df149 commit b16d963
Show file tree
Hide file tree
Showing 51 changed files with 1,991 additions and 36 deletions.
1 change: 0 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,5 @@ FROM alpine:latest

COPY --from=build-env /go/bin/blog /go/bin/blog
COPY ./views /go/bin/views
COPY ./static /go/bin/static
WORKDIR /go/bin/
CMD ["/go/bin/blog", "start", "-p", ":8080", "-c", "/etc/blog/app.cfg"]
4 changes: 3 additions & 1 deletion cmd/service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,9 @@ func start() {
mux.Handle("/", home.MakeHandler(homeSvc, httpLogger))

http.Handle("/metrics", promhttp.Handler())
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("./views/tonight/images/"))))
http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("./views/tonight/css/"))))
http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("./views/tonight/js/"))))
http.Handle("/", accessControl(mux, logger))

errs := make(chan error, 2)
Expand Down
13 changes: 11 additions & 2 deletions src/pkg/home/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/nsini/blog/src/config"
"github.com/nsini/blog/src/pkg/post"
"github.com/nsini/blog/src/repository"
"strconv"
)
Expand Down Expand Up @@ -76,12 +77,20 @@ func (c *service) Index(ctx context.Context) (rs map[string]interface{}, err err
"comment": v.Reviews,
"image_url": imgUrl,
"desc": v.Description,
"tags": v.Tags,
"id": strconv.Itoa(int(v.ID)),
})
}

postSvc := post.NewService(c.logger, c.config, c.repository)
res, _ := postSvc.Popular(ctx)

total, _ := c.repository.Post().Count()

return map[string]interface{}{
"stars": starsData,
"list": posts,
"stars": starsData,
"list": posts,
"populars": res,
"total": total,
}, nil
}
5 changes: 1 addition & 4 deletions src/pkg/home/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,7 @@ func encodeIndexResponse(ctx context.Context, w http.ResponseWriter, response in

resp := response.(indexResponse)

return templates.RenderHtml(ctx, w, map[string]interface{}{
"stars": resp.Data["stars"],
"list": resp.Data["list"],
})
return templates.RenderHtml(ctx, w, resp.Data)
}

type errorer interface {
Expand Down
31 changes: 19 additions & 12 deletions src/pkg/post/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@ type paginator struct {
}

type listResponse struct {
Data []map[string]interface{} `json:"data,omitempty"`
Count int64 `json:"count,omitempty"`
Paginator paginator `json:"paginator,omitempty"`
Err error `json:"error,omitempty"`
Data map[string]interface{} `json:"data,omitempty"`
Count int64 `json:"count,omitempty"`
Paginator paginator `json:"paginator,omitempty"`
Err error `json:"error,omitempty"`
}

func (r listResponse) error() error { return r.Err }
Expand All @@ -51,15 +51,22 @@ func makeGetEndpoint(s Service) endpoint.Endpoint {
}

func makeListEndpoint(s Service) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(listRequest)
rs, count, err := s.List(ctx, req.order, req.by, req.action, req.pageSize, req.offset)
pager := paginator{
By: req.by,
Offset: req.offset,
PageSize: req.pageSize,
}
return listResponse{rs, count, pager, err}, err
rs, count, other, err := s.List(ctx, req.order, req.by, req.action, req.pageSize, req.offset)
return listResponse{
Data: map[string]interface{}{
"post": rs,
"other": other,
},
Count: count,
Paginator: paginator{
By: req.by,
Offset: req.offset,
PageSize: req.pageSize,
},
Err: err,
}, err
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/pkg/post/instrumenting.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func (s *instrumentingService) Get(ctx context.Context, id int64) (rs map[string
return s.Service.Get(ctx, id)
}

func (s *instrumentingService) List(ctx context.Context, order, by string, action, pageSize, offset int) (rs []map[string]interface{}, count int64, err error) {
func (s *instrumentingService) List(ctx context.Context, order, by string, action, pageSize, offset int) (rs []map[string]interface{}, count int64, other map[string]interface{}, err error) {
defer func(begin time.Time) {
s.requestCount.With("method", "list").Add(1)
s.requestLatency.With("method", "list").Observe(time.Since(begin).Seconds())
Expand Down
2 changes: 1 addition & 1 deletion src/pkg/post/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func (s *loggingService) Get(ctx context.Context, id int64) (rs map[string]inter
return s.Service.Get(ctx, id)
}

func (s *loggingService) List(ctx context.Context, order, by string, action, pageSize, offset int) (rs []map[string]interface{}, count int64, err error) {
func (s *loggingService) List(ctx context.Context, order, by string, action, pageSize, offset int) (rs []map[string]interface{}, count int64, other map[string]interface{}, err error) {
defer func(begin time.Time) {
_ = s.logger.Log(
"method", "List",
Expand Down
25 changes: 23 additions & 2 deletions src/pkg/post/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ var ErrInvalidArgument = errors.New("invalid argument")

type Service interface {
Get(ctx context.Context, id int64) (rs map[string]interface{}, err error)
List(ctx context.Context, order, by string, action, pageSize, offset int) (rs []map[string]interface{}, count int64, err error)
List(ctx context.Context, order, by string, action, pageSize, offset int) (rs []map[string]interface{}, count int64, other map[string]interface{}, err error)
Popular(ctx context.Context) (rs []map[string]interface{}, err error)
}

Expand Down Expand Up @@ -50,6 +50,12 @@ func (c *service) Get(ctx context.Context, id int64) (rs map[string]interface{},
headerImage = c.config.GetString("server", "image_domain") + "/" + image.ImagePath
}

// prev
prev, _ := c.repository.Post().Prev(detail.PushTime)
// next
next, _ := c.repository.Post().Next(detail.PushTime)

populars, _ := c.Popular(ctx)
return map[string]interface{}{
"content": detail.Content,
"title": detail.Title,
Expand All @@ -58,13 +64,20 @@ func (c *service) Get(ctx context.Context, id int64) (rs map[string]interface{},
"author": detail.User.Username,
"comment": detail.Reviews,
"banner_image": headerImage,
"read_num": strconv.Itoa(int(detail.ReadNum)),
"description": detail.Description,
"tags": detail.Tags,
"populars": populars,
"prev": prev,
"next": next,
}, nil
}

/**
* @Title 列表页
*/
func (c *service) List(ctx context.Context, order, by string, action, pageSize, offset int) (rs []map[string]interface{}, count int64, err error) {
func (c *service) List(ctx context.Context, order, by string, action, pageSize, offset int) (rs []map[string]interface{},
count int64, other map[string]interface{}, err error) {
// 取列表 判断搜索、分类、Tag条件
// 取最多阅读

Expand Down Expand Up @@ -108,6 +121,14 @@ func (c *service) List(ctx context.Context, order, by string, action, pageSize,
})
}

tags, _ := c.repository.Tag().List(20)

populars, _ := c.Popular(ctx)
other = map[string]interface{}{
"tags": tags,
"populars": populars,
}

return
}

Expand Down
26 changes: 17 additions & 9 deletions src/pkg/post/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/gorilla/mux"
"github.com/nsini/blog/src/repository"
"github.com/nsini/blog/src/templates"
"math"
"net/http"
"strconv"
"strings"
Expand Down Expand Up @@ -121,7 +122,7 @@ func encodeDetailResponse(ctx context.Context, w http.ResponseWriter, response i
return nil
}

ctx = context.WithValue(ctx, "method", "blog-single")
ctx = context.WithValue(ctx, "method", "info")

resp := response.(postResponse)

Expand All @@ -134,12 +135,17 @@ func encodeListResponse(ctx context.Context, w http.ResponseWriter, response int
return nil
}

ctx = context.WithValue(ctx, "method", "blog-left-sidebar")
ctx = context.WithValue(ctx, "method", "list")

resp := response.(listResponse)

other := resp.Data["other"].(map[string]interface{})

return templates.RenderHtml(ctx, w, map[string]interface{}{
"list": resp.Data,
"list": resp.Data["post"],
"tags": other["tags"],
"populars": other["populars"],
"total": strconv.Itoa(int(resp.Count)),
"paginator": postPaginator(int(resp.Count), resp.Paginator.PageSize, resp.Paginator.Offset),
})
}
Expand All @@ -155,16 +161,18 @@ func postPaginator(count, pageSize, offset int) string {
if offset+pageSize > count {
next = offset
}
res = append(res, fmt.Sprintf(`<li><a href="/post?pageSize=10&offset=%d">Prev</a></li>`, prev))
for i := 1; i <= (count / pageSize); i++ {
res = append(res, fmt.Sprintf(`<a href="/post?pageSize=10&offset=%d">上一页</a>&nbsp;`, prev))

length := math.Ceil(float64(count) / float64(pageSize))
for i := 1; i <= int(length); i++ {
os := (i - 1) * 10
var active string
if offset == os {
active = `class="active"`
res = append(res, fmt.Sprintf(`<b>%d</b>`, i))
continue
}
res = append(res, fmt.Sprintf(`<li %s><a href="/post?pageSize=10&offset=%d">%d</a></li>`, active, os, i))
res = append(res, fmt.Sprintf(`<a href="/post?pageSize=10&offset=%d">%d</a>&nbsp;`, os, i))
}
res = append(res, fmt.Sprintf(`<li><a href="/post?pageSize=10&offset=%d">Next</a></li>`, next))
res = append(res, fmt.Sprintf(`<a href="/post?pageSize=10&offset=%d">下一页</a>&nbsp;`, next))
return strings.Join(res, "\n")
}

Expand Down
30 changes: 28 additions & 2 deletions src/repository/post.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"github.com/jinzhu/gorm"
"github.com/nsini/blog/src/repository/types"
"time"
)

var (
Expand All @@ -19,6 +20,9 @@ type PostRepository interface {
Update(p *types.Post) error
Stars() (res []*types.Post, err error)
Index() (res []*types.Post, err error)
Prev(publishTime *time.Time) (res *types.Post, err error)
Next(publishTime *time.Time) (res *types.Post, err error)
Count() (total int64, err error)
}

type PostStatus string
Expand All @@ -32,6 +36,27 @@ type post struct {
db *gorm.DB
}

func (c *post) Count() (total int64, err error) {
err = c.db.Model(&types.Post{}).Where("post_status = ?", PostStatusPublish).Count(&total).Error
return
}

func (c *post) Prev(publishTime *time.Time) (res *types.Post, err error) {
var p types.Post
err = c.db.Where("push_time < ?", publishTime).
Where("post_status = ?", PostStatusPublish).
Order("push_time desc").Limit(1).First(&p).Error
return &p, err
}

func (c *post) Next(publishTime *time.Time) (res *types.Post, err error) {
var p types.Post
err = c.db.Where("push_time > ?", publishTime).
Where("post_status = ?", PostStatusPublish).
Order("push_time asc").Limit(1).First(&p).Error
return &p, err
}

func NewPostRepository(db *gorm.DB) PostRepository {
return &post{db: db}
}
Expand All @@ -40,6 +65,7 @@ func (c *post) Index() (res []*types.Post, err error) {
err = c.db.Where("post_status = ?", PostStatusPublish).
Preload("Images").
Preload("User").
Preload("Tags").
Order(gorm.Expr("push_time DESC")).
Limit(10).Find(&res).Error

Expand All @@ -51,7 +77,7 @@ func (c *post) Stars() (res []*types.Post, err error) {
Where("post_status = ?", PostStatusPublish).
Preload("Images").
Order(gorm.Expr("push_time DESC")).
Limit(5).Find(&res).Error
Limit(7).Find(&res).Error
return
}

Expand Down Expand Up @@ -91,7 +117,7 @@ func (c *post) FindBy(action []int, order, by string, pageSize, offset int) ([]*
}

func (c *post) Popular() (posts []*types.Post, err error) {
if err = c.db.Order("read_num DESC").Limit(5).Find(&posts).Error; err != nil {
if err = c.db.Order("read_num DESC").Limit(9).Find(&posts).Error; err != nil {
return
}
return
Expand Down
6 changes: 6 additions & 0 deletions src/repository/tag.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,18 @@ const (

type TagRepository interface {
FirstOrCreate(name string) (meta *types.Tag, err error)
List(limit int) (metas []*types.Tag, err error)
}

type tag struct {
db *gorm.DB
}

func (c *tag) List(limit int) (metas []*types.Tag, err error) {
err = c.db.Model(&types.Tag{}).Order("id desc").Limit(limit).Find(&metas).Error
return
}

func NewTagRepository(db *gorm.DB) TagRepository {
return &tag{db: db}
}
Expand Down
2 changes: 1 addition & 1 deletion src/templates/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func RenderHtml(ctx context.Context, w http.ResponseWriter, response map[string]
name := ctx.Value("method").(string)

buf := new(bytes.Buffer)
if err := Render(response, buf, "views/default/"+name); err != nil {
if err := Render(response, buf, "views/tonight/"+name); err != nil {
return err
}

Expand Down
12 changes: 12 additions & 0 deletions views/tonight/404.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{% extends "default-layout.html" %}

{% block body %}
<article>
<div class="whitebg about">
<h1>404</h1>
<h2>page not found</h2>
<h3>Sorry, the site now can not be accessed.</h3>
<a href="/">返回首页</a>
</div>
</article>
{% endblock %}
Loading

0 comments on commit b16d963

Please sign in to comment.