/
service.go
95 lines (75 loc) · 1.64 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package postmi
import (
"fmt"
"github.com/gin-gonic/gin"
"gopkg.in/gcfg.v1"
"net/http"
)
type Service struct {
Store Store
Config
}
func New(confPath string) (*Service, error) {
var cfg Config
e := gcfg.ReadFileInto(&cfg, confPath)
if e != nil {
return nil, e
}
return NewWithConfig(cfg)
}
func NewWithConfig(cfg Config) (*Service, error) {
s := new(Service)
s.Config = cfg
store, e := Open(cfg.DataBase.Driver, cfg.DataBase.Setting)
if e != nil {
return nil, e
}
s.Store = store
return s, nil
}
func (s *Service) Run() error {
eng := gin.Default()
eng.LoadHTMLGlob(s.Config.App.TemplatesPath + "/*")
eng.Static("/assets", s.Config.App.AssetPath)
prefix := "/"
if s.Config.App.Prefix != "" {
prefix = s.Config.App.Prefix
}
g := eng.Group(prefix, gin.BasicAuth(gin.Accounts{
s.Config.Admin.Login: s.Config.Admin.Password,
}))
g.GET("/", func(c *gin.Context) {
posts, e := s.Store.GetSlice(10, 0)
res := gin.H{}
if e != nil {
fmt.Println(e)
res["error"] = e
}
res["posts"] = posts
c.HTML(200, "index.html", res)
})
g.Any("/create", func(c *gin.Context) {
rm := gin.H{}
if c.Request.Method == "POST" {
rm["message"] = "posted"
title := c.PostForm("title")
content := c.PostForm("content")
p := new(Post)
p.Title = title
p.Body = content
e := s.Store.Save(p)
if e != nil {
fmt.Println(e)
rm["error"] = e
}
}
c.HTML(200, "edit.html", rm)
})
g.GET("/p/:id", func(c *gin.Context) {
id := c.Param("id")
c.HTML(200, "show.html", gin.H{"da": id})
})
g.POST("/p/:id", func(c *gin.Context) {
})
return http.ListenAndServe(fmt.Sprintf(":%d", s.Config.App.Port), eng)
}