Skip to content

Commit

Permalink
refactor: new (#3)
Browse files Browse the repository at this point in the history
* Add new files and modify existing files

* Add new templates and API endpoint for user login and registration

* Add PostForm and Post model
  • Loading branch information
funnyzak authored Feb 7, 2024
1 parent cff3ab0 commit 3d11245
Show file tree
Hide file tree
Showing 51 changed files with 1,058 additions and 592 deletions.
36 changes: 28 additions & 8 deletions cmd/main.go
Original file line number Diff line number Diff line change
@@ -1,32 +1,52 @@
package main

import (
"go-gin/cmd/srv"
"context"
"go-gin/cmd/srv/controller"
"go-gin/service/singleton"

"github.com/ory/graceful"
flag "github.com/spf13/pflag"
)

type CliParam struct {
ConfigName string // 配置文件名称
ConfigName string // Config file name
Port uint // Server port
}

var (
svrCliParam CliParam
cliParam CliParam
)

func main() {
flag.CommandLine.ParseErrorsWhitelist.UnknownFlags = true
flag.StringVarP(&svrCliParam.ConfigName, "config", "c", "config", "config file name")
flag.StringVarP(&cliParam.ConfigName, "config", "c", "config", "config file name")
flag.UintVarP(&cliParam.Port, "port", "p", 0, "server port")
flag.Parse()
flag.Lookup("config").NoOptDefVal = "config"

singleton.InitConfig(svrCliParam.ConfigName)
singleton.InitLog(singleton.Config)
// singleton.InitDBFromPath(singleton.Config.DB_Path)
singleton.InitConfig(cliParam.ConfigName)
singleton.InitLog(singleton.Conf)
singleton.InitDBFromPath(singleton.Conf.DBPath)
initService()

srv.ServerWeb(singleton.Config)
port := singleton.Conf.Server.Port
if cliParam.Port != 0 {
port = cliParam.Port
}

srv := controller.ServerWeb(port)

if err := graceful.Graceful(func() error {
return srv.ListenAndServe()
}, func(c context.Context) error {
singleton.Log.Info().Msg("Graceful::START")
srv.Shutdown(c)
return nil
}); err != nil {
singleton.Log.Err(err).Msg("Graceful::Error")
}

}

func initService() {
Expand Down
57 changes: 57 additions & 0 deletions cmd/srv/controller/api_v1.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package controller

import (
"fmt"
"go-gin/internal/gogin"
"go-gin/service/singleton"

"github.com/gin-gonic/gin"
)

type apiV1 struct {
r gin.IRouter
}

func (v *apiV1) serve() {
r := v.r.Group("")
// API
r.Use(gogin.Authorize(gogin.AuthorizeOption{
User: true,
IsPage: false,
Msg: "Please log in first",
Btn: "Log in",
Redirect: fmt.Sprintf("%s/login", singleton.Conf.Site.BaseURL),
}))
r.PUT("/post", v.putPost)

user := v.r.Group("user")
{
user.GET("/info", v.getUserInfo)
user.GET("/logout", v.logout)
user.GET("/refresh", v.refresh)
}
}

func (v *apiV1) putPost(c *gin.Context) {
c.JSON(200, gin.H{
"message": "post",
})
}

func (v *apiV1) getUserInfo(c *gin.Context) {
c.JSON(200, gin.H{
"message": "user info",
})
}

func (v *apiV1) logout(c *gin.Context) {
c.JSON(200, gin.H{
"message": "logout",
})
}

func (v *apiV1) refresh(c *gin.Context) {
c.JSON(200, gin.H{
"message": "refresh",
})
}
103 changes: 0 additions & 103 deletions cmd/srv/controller/auth.go

This file was deleted.

26 changes: 0 additions & 26 deletions cmd/srv/controller/common.go

This file was deleted.

28 changes: 28 additions & 0 deletions cmd/srv/controller/common_page.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package controller

import (
"go-gin/internal/gogin"
"net/http"

"github.com/gin-gonic/gin"
)

type commonPage struct {
r *gin.Engine
}

func (cp *commonPage) serve() {
cr := cp.r.Group("")
cr.GET("/", cp.home)
cr.GET("/ping", cp.ping)
}

func (p *commonPage) home(c *gin.Context) {
c.HTML(http.StatusOK, "index", gogin.CommonEnvironment(c, gin.H{}))
}

func (p *commonPage) ping(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
}
107 changes: 107 additions & 0 deletions cmd/srv/controller/controller.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package controller

import (
"fmt"
"html/template"
"io/fs"
"net/http"
"time"

"github.com/gin-contrib/pprof"
"github.com/gin-gonic/gin"

"go-gin/internal/gconfig"
"go-gin/internal/gogin"
"go-gin/pkg/mygin"
"go-gin/resource"
"go-gin/service/singleton"
)

func ServerWeb(port uint) *http.Server {
gin.SetMode(gin.ReleaseMode)
r := gin.Default()

loadTemplates(r)

if singleton.Conf.Debug {
gin.SetMode(gin.DebugMode)
pprof.Register(r, gconfig.DefaultPprofRoutePath)
}

r.Use(mygin.RecordPath)

serveStatic(r)

routers(r)

srv := &http.Server{
Addr: fmt.Sprintf(":%d", port),
ReadHeaderTimeout: time.Second * 5,
Handler: r,
}
return srv
}

// Serve static files
func serveStatic(r *gin.Engine) {
staticFs, err := fs.Sub(resource.StaticFS, "static")
if err != nil {
singleton.Log.Fatal().Err(err).Msg("Error parsing static files")
panic(err)
}
r.StaticFS("/static", http.FS(staticFs))

// Serve uploaded files
r.Static("/upload", singleton.Conf.Upload.Dir)
}

// Load templates
func loadTemplates(r *gin.Engine) {
new_tmpl := template.New("").Funcs(mygin.FuncMap)
var err error
new_tmpl, err = new_tmpl.ParseFS(resource.TemplateFS, "template/**/*.html", "template/*.html")
if err != nil {
singleton.Log.Fatal().Err(err).Msg("Error parsing templates")
panic(err)
}
r.SetHTMLTemplate(new_tmpl)
}

func routers(r *gin.Engine) {

r.Use(gogin.LoggingHandler())
r.Use(mygin.GenerateContextIdHandler())
r.Use(mygin.CORSHandler())
r.Use(gogin.RateLimiterHandler(singleton.Conf.RateLimit.Max))

// Serve common pages, e.g. home, ping
cp := commonPage{r: r}
cp.serve()

// Serve guest pages, e.g. register, login
gp := guestPage{r: r}
gp.serve()

// Server show pages, e.g. post
sp := showPage{r: r}
sp.serve()

// Serve API
api := r.Group("api")
{
ua := &userAPI{r: api}
ua.serve()
}

page404 := func(c *gin.Context) {
gogin.ShowErrorPage(c, mygin.ErrInfo{
Code: http.StatusNotFound,
Title: "Page not found",
Msg: "The page you are looking for is not found",
Link: singleton.Conf.Site.BaseURL,
Btn: "Back to home",
}, true)
}
r.NoRoute(page404)
r.NoMethod(page404)
}
Loading

0 comments on commit 3d11245

Please sign in to comment.