Browse Source

refactor: remove unneeded code

dev
Evan 9 months ago
parent
commit
3e093651ec
  1. 0
      .drone.yml
  2. 3
      Makefile
  3. 5
      cmd/admin.go
  4. 22
      cmd/cmd.go
  5. 20
      internal/logger/logger.go
  6. 25
      internal/resource/error.go
  7. 31
      internal/resource/response.go
  8. 35
      internal/response/response.go
  9. 5
      internal/util/write_to_config.go
  10. 3
      main.go
  11. 8
      models/user.go
  12. 14
      services/auth/auth.go
  13. 10
      services/auth/user.go
  14. 4
      services/calendar/calendar.go
  15. 10
      services/services.go
  16. 8
      services/services_min.go

0
.drone.yml

3
Makefile

@ -10,8 +10,7 @@ GOPATH := $(GOBASE)/vendor:$(GOBASE)
GOBIN := $(GOBASE)/bin
GOFILES := main.go
LDFLAG=-X 'github.com/mutsuki333/calendar/cmd.Version=$(VERSION)-$(BUILD)'
LDFLAG+=-X 'github.com/mutsuki333/calendar/services.Version=$(VERSION)-$(BUILD)'
LDFLAG=-X 'main.Version=$(VERSION)-$(BUILD)'
LDFLAGS=-ldflags="-w $(LDFLAG)"
# MAKEFLAGS += --silent

5
cmd/admin.go

@ -1,7 +1,8 @@
package cmd
import (
"github.com/mutsuki333/calendar/internal/logger"
"log"
"github.com/spf13/cobra"
)
@ -9,7 +10,7 @@ var adminCmd = &cobra.Command{
Use: "admin",
Short: "Calendar server admin",
RunE: func(cmd *cobra.Command, args []string) error {
logger.Dbg.Println("Nothing yet")
log.Println("Nothing yet")
return nil
},
}

22
cmd/cmd.go

@ -2,6 +2,8 @@ package cmd
import (
"fmt"
"log"
"os"
"github.com/pkg/browser"
@ -14,14 +16,20 @@ import (
"github.com/robfig/cron/v3"
)
var Version = "development"
var version = "development"
//SetVersionInfo setup version info
func SetVersionInfo(ver string) {
version = ver
RootCmd.Version = ver
}
var RootCmd = &cobra.Command{
Use: "calendar [-flags] [args]",
Short: "A go calendar server",
Long: `
Starts the calendar server`,
Version: Version,
Version: version,
RunE: start,
}
@ -42,6 +50,15 @@ func init() {
RootCmd.PersistentFlags().Bool("save", false, "Save config for future usage.")
RootCmd.PersistentFlags().StringP("yaml", "y", viper.GetString("data"), "Location of config file to read from.")
file, err := os.OpenFile("info.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
log.SetOutput(file)
log.Print("Server started!")
}
func start(cmd *cobra.Command, args []string) error {
@ -57,6 +74,7 @@ func start(cmd *cobra.Command, args []string) error {
c := cron.New()
c.AddFunc("30 * * * *", func() { fmt.Println("Every half hour") })
c.Start()
services.SetVersionInfo(version)
services.Start()
return nil
}

20
internal/logger/logger.go

@ -1,20 +0,0 @@
package logger
import (
"log"
"os"
)
var (
Dbg *log.Logger
Inf *log.Logger
Wrn *log.Logger
Err *log.Logger
)
func init() {
Dbg = log.New(os.Stdout, "DEBUG: ", log.Ldate|log.Ltime|log.Lshortfile)
Inf = log.New(os.Stdout, "INFO: ", log.Ldate|log.Ltime)
Wrn = log.New(os.Stdout, "WARN: ", log.Ldate|log.Ltime|log.Lshortfile)
Err = log.New(os.Stderr, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile)
}

25
internal/resource/error.go

@ -1,25 +0,0 @@
package resource
import (
"net/http"
"github.com/gin-gonic/gin"
)
type RequestError struct {
Message string `json:"message" example:"status bad request"`
}
type BaseError struct {
Code int `json:"code" example:"400"`
Message string `json:"message" example:"status bad request"`
}
//NotFound Response err with 400
func Abort(ctx *gin.Context, err error) {
er := BaseError{
Code: http.StatusBadRequest,
Message: err.Error(),
}
ctx.AbortWithStatusJSON(http.StatusBadRequest, er)
}

31
internal/resource/response.go

@ -1,31 +0,0 @@
package resource
import (
"net/http"
"github.com/gin-gonic/gin"
)
//BaseResponse base response structure
type BaseResponse struct {
Code int `json:"code" example:"200"`
Message string `json:"message" example:"ok"`
}
//MakeResponse returns 200 with simple *msg*
func MakeResponse(ctx *gin.Context, msg string) {
res := BaseResponse{
Code: http.StatusOK,
Message: msg,
}
ctx.JSON(http.StatusOK, res)
}
//Ok returns 200 with message:"ok"
func Ok(ctx *gin.Context) {
res := BaseResponse{
Code: http.StatusOK,
Message: "ok",
}
ctx.JSON(http.StatusOK, res)
}

35
internal/response/response.go

@ -0,0 +1,35 @@
package response
import (
"net/http"
"github.com/gin-gonic/gin"
)
//MakeResponse returns 200 with simple *msg*
func MakeResponse(ctx *gin.Context, msg string) {
ctx.JSON(http.StatusOK, gin.H{
"message": msg,
})
}
//Ok returns 200 with message:"ok"
func Ok(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"message": "ok",
})
}
//AbortError abort with error
func AbortError(ctx *gin.Context, err error) {
ctx.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
}
//Abort abort with error
func Abort(ctx *gin.Context, code int, msg string) {
ctx.AbortWithStatusJSON(code, gin.H{
"message": msg,
})
}

5
internal/util/write_to_config.go

@ -1,11 +1,10 @@
package util
import (
"log"
"os"
"path/filepath"
"github.com/mutsuki333/calendar/internal/logger"
"github.com/spf13/viper"
)
@ -25,7 +24,7 @@ func ReadConfig(path string) {
//WriteConfig Writes config at *path*
func WriteConfig(path string) {
viper.WriteConfigAs(getConfigFile(path))
logger.Inf.Println("Config saved.")
log.Println("Config saved.")
}
func getConfigFile(path string) string {

3
main.go

@ -4,8 +4,11 @@ import (
"github.com/mutsuki333/calendar/cmd"
)
var Version = "development"
//go:generate statik -src=ui/dist -dest=assets -f
//go:generate swag init -g services/services.go
func main() {
cmd.SetVersionInfo(Version)
cmd.RootCmd.Execute()
}

8
models/user.go

@ -2,10 +2,10 @@ package models
import (
"errors"
"log"
"strings"
"github.com/mutsuki333/calendar/internal/constants"
"github.com/mutsuki333/calendar/internal/logger"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
@ -27,7 +27,7 @@ func (usr *User) ChangePassword(to string) (err error) {
return err
}
if err := db.Model(&usr).Update("password", string(bytes)).Error; err != nil {
logger.Dbg.Println(err)
log.Println(err)
}
return err
}
@ -42,7 +42,7 @@ func (usr *User) ValidatePassword(pwd string) error {
func InsertUser(name, email, password string) error {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
if err != nil {
logger.Err.Println(err)
log.Println(err)
return err
}
user := &User{
@ -52,7 +52,7 @@ func InsertUser(name, email, password string) error {
Level: constants.User,
}
if err := db.Create(&user).Error; err != nil {
logger.Err.Println(err)
log.Println(err)
return errors.New("creating error")
}
return nil

14
services/auth/auth.go

@ -5,7 +5,7 @@ import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/mutsuki333/calendar/internal/resource"
"github.com/mutsuki333/calendar/internal/response"
"github.com/mutsuki333/calendar/models"
"github.com/mutsuki333/calendar/modules/authenticate"
)
@ -52,25 +52,25 @@ type loginRequest struct {
func login(c *gin.Context) {
var param loginRequest
if err := c.ShouldBindJSON(&param); err != nil {
resource.Abort(c, err)
response.AbortError(c, err)
return
}
user, err := models.GetUser(param.Username)
if err != nil {
resource.Abort(c, err)
response.AbortError(c, err)
return
}
pwd, err := base64.URLEncoding.DecodeString(param.PwdB64)
if err != nil {
resource.Abort(c, err)
response.AbortError(c, err)
return
}
if err := user.ValidatePassword(string(pwd)); err != nil {
resource.Abort(c, err)
response.AbortError(c, err)
return
}
authenticate.LoginUser(c, user.ID)
resource.Ok(c)
response.Ok(c)
}
@ -82,7 +82,7 @@ func login(c *gin.Context) {
// @Router /auth/logout [post]
func logout(c *gin.Context) {
authenticate.LogoutUser(c)
resource.Ok(c)
response.Ok(c)
}
// @Summary Get Token

10
services/auth/user.go

@ -3,12 +3,12 @@ package auth
import (
"encoding/base64"
"fmt"
"log"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/mutsuki333/calendar/internal/logger"
"github.com/mutsuki333/calendar/internal/resource"
"github.com/mutsuki333/calendar/internal/response"
"github.com/mutsuki333/calendar/models"
)
@ -46,7 +46,7 @@ func postUser(c *gin.Context) {
return
}
logger.Dbg.Println(data)
log.Println(data)
pwd, err := base64.URLEncoding.DecodeString(data.PwdB64)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
@ -88,12 +88,12 @@ func listUsers(c *gin.Context) {
func getUser(c *gin.Context) {
userID, err := strconv.Atoi(c.Param("id"))
if err != nil {
resource.Abort(c, err)
response.AbortError(c, err)
return
}
user, err := models.LoadUser(uint(userID))
if err != nil {
resource.Abort(c, err)
response.AbortError(c, err)
return
}
c.JSON(200, user)

4
services/calendar/calendar.go

@ -1,10 +1,10 @@
package calendar
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
"github.com/mutsuki333/calendar/internal/logger"
"github.com/mutsuki333/calendar/models"
)
@ -42,7 +42,7 @@ func listCalendars(c *gin.Context) {
// @Router /calendar/{calendarID} [get]
func getCalendar(c *gin.Context) {
calendarID := c.Param("calendarID")
logger.Dbg.Println(calendarID)
log.Println(calendarID)
c.JSON(200, gin.H{
"message": "update user",
})

10
services/services.go

@ -17,8 +17,12 @@ import (
ginSwagger "github.com/swaggo/gin-swagger"
)
//Version shows the version of the build.
var Version = "development"
var version = "development"
//SetVersionInfo setup version info
func SetVersionInfo(ver string) {
version = ver
}
//Start starts the service server.
// @title Calendar API
@ -56,7 +60,7 @@ func Start() {
if viper.GetBool("swagger.enabled") {
docs.SwaggerInfo.Host = ""
docs.SwaggerInfo.BasePath = "/api"
docs.SwaggerInfo.Version = Version
docs.SwaggerInfo.Version = version
server.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
}

8
services/services_min.go

@ -12,8 +12,12 @@ import (
"github.com/spf13/viper"
)
//Version shows the version of the build.
var Version = "development"
var version = "development"
//SetVersionInfo setup version info
func SetVersionInfo(ver string) {
version = ver
}
//Start starts the service server.
func Start() {