Skip to content

Commit

Permalink
Add JSON utility functions, Viper configuration reader, IP utility fu…
Browse files Browse the repository at this point in the history
…nctions, and file utility functions
  • Loading branch information
funnyzak committed Feb 20, 2024
1 parent e0d9ed7 commit 56bac1e
Show file tree
Hide file tree
Showing 12 changed files with 198 additions and 171 deletions.
12 changes: 7 additions & 5 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@ package main
import (
"context"
"fmt"
"go-gin/cmd/srv/controller"
"go-gin/pkg/mygin"
"go-gin/pkg/utils"
"go-gin/service/singleton"

"github.com/gin-gonic/gin"
"github.com/ory/graceful"
flag "github.com/spf13/pflag"

"go-gin/cmd/srv/controller"
"go-gin/pkg/mygin"
"go-gin/pkg/utils"
"go-gin/pkg/utils/ip"
"go-gin/service/singleton"
)

type CliParam struct {
Expand Down Expand Up @@ -58,7 +60,7 @@ func main() {
fmt.Println()
fmt.Println("Server is running at:")
fmt.Printf(" - %-7s: %s\n", "Local", utils.Colorize(utils.ColorGreen, fmt.Sprintf("http://127.0.0.1:%d", port)))
ipv4s, err := utils.GetIPv4NetworkIPs()
ipv4s, err := ip.GetIPv4NetworkIPs()
if ipv4s != nil && err == nil {
for _, ip := range ipv4s {
fmt.Printf(" - %-7s: %s\n", "Network", utils.Colorize(utils.ColorGreen, fmt.Sprintf("http://%s:%d", ip, port)))
Expand Down
8 changes: 4 additions & 4 deletions cmd/srv/controller/api_v1.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"go-gin/mappers"
"go-gin/model"
"go-gin/pkg/mygin"
"go-gin/pkg/utils"
"go-gin/pkg/utils/parse"
"go-gin/service/singleton"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -43,7 +43,7 @@ func (v *apiV1) serve() {
var authModel = model.Auth{}

func (v *apiV1) logout(c *gin.Context) {
isPage := utils.ParseBool(c.Query("page"), false)
isPage := parse.ParseBool(c.Query("page"), false)
gogin.UserLogout(c)
if isPage {
gogin.ShowMessagePage(c, "Logout success", singleton.Conf.Site.BaseURL, "Back to home")
Expand All @@ -54,7 +54,7 @@ func (v *apiV1) logout(c *gin.Context) {

func (v *apiV1) refresh(c *gin.Context) {
var tokenForm mappers.Token
if err := mygin.BindForm(c, utils.ParseBool("form", false), &tokenForm); err != nil {
if err := mygin.BindForm(c, parse.ParseBool("form", false), &tokenForm); err != nil {
mygin.ResponseJSON(c, 400, gin.H{}, "refresh token is required")
return
}
Expand All @@ -68,7 +68,7 @@ func (v *apiV1) refresh(c *gin.Context) {

func (v *apiV1) postPost(c *gin.Context) {
var postForm mappers.PostForm
isForm := utils.ParseBool(c.Query("form"), false)
isForm := parse.ParseBool(c.Query("form"), false)
if err := mygin.BindForm(c, isForm, &postForm); err != nil {
gogin.ShowErrorPage(c, mygin.ErrInfo{
Code: 400,
Expand Down
4 changes: 2 additions & 2 deletions cmd/srv/controller/show_page.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"go-gin/internal/gogin"
"go-gin/model"
"go-gin/pkg/mygin"
"go-gin/pkg/utils"
"go-gin/pkg/utils/parse"
"go-gin/service/singleton"
"net/http"

Expand All @@ -24,7 +24,7 @@ func (sp *showPage) serve() {
}

func (sp *showPage) postDetail(c *gin.Context) {
postId := utils.ParseInt(c.Param("id"), 0)
postId := parse.ParseInt(c.Param("id"), 0)
if postId <= 0 {
gogin.ShowErrorPage(c, mygin.ErrInfo{
Msg: "Post not found",
Expand Down
6 changes: 3 additions & 3 deletions cmd/srv/controller/user_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"go-gin/mappers"
"go-gin/model"
"go-gin/pkg/mygin"
"go-gin/pkg/utils"
"go-gin/pkg/utils/parse"
"go-gin/service/singleton"
"net/http"

Expand All @@ -32,7 +32,7 @@ func (ua *userAPI) serve() {
func (ua *userAPI) login(c *gin.Context) {
var loginForm mappers.LoginForm

isPage := utils.ParseBool(c.Query("page"), false)
isPage := parse.ParseBool(c.Query("page"), false)
showError := func(err error) {
gogin.ShowErrorPage(c, mygin.ErrInfo{
Title: "Login failed",
Expand Down Expand Up @@ -68,7 +68,7 @@ func (ua *userAPI) login(c *gin.Context) {
func (ua *userAPI) register(c *gin.Context) {
var registerForm mappers.RegisterForm

isPage := utils.ParseBool(c.Query("page"), false)
isPage := parse.ParseBool(c.Query("page"), false)
showError := func(err error) {
gogin.ShowErrorPage(c, mygin.ErrInfo{
Title: "Register failed",
Expand Down
2 changes: 1 addition & 1 deletion pkg/utils/viper.go → pkg/utils/conf/viper.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package utils
package conf

import (
"github.com/spf13/viper"
Expand Down
56 changes: 56 additions & 0 deletions pkg/utils/file/file.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package file

import (
"crypto/md5"
"encoding/hex"
"io"
"os"
"path"
"path/filepath"
)

func FilExists(filename string) bool {
_, err := os.Stat(filename)
return !os.IsNotExist(err)
}

func WriteToFile(filePath string, content string, filemode os.FileMode) error {
if err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
return err
}

if err := os.WriteFile(filePath, []byte(content), filemode); err != nil {
return err
}
return nil
}

func FileMD5(filePath string) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", err
}
defer file.Close()

hash := md5.New()
if _, err := io.Copy(hash, file); err != nil {
return "", err
}

hashInBytes := hash.Sum(nil)
md5Hash := hex.EncodeToString(hashInBytes)

return md5Hash, nil
}

func MkdirAllIfNotExists(pathname string, perm os.FileMode) error {
dir := path.Dir(pathname)
if _, err := os.Stat(dir); err != nil {
if os.IsNotExist(err) {
if err := os.MkdirAll(dir, perm); err != nil {
return err
}
}
}
return nil
}
46 changes: 46 additions & 0 deletions pkg/utils/ip/ip.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package ip

import (
"net"
)

func GetIPv4NetworkIPs() ([]string, error) {
ips, err := GetNetworkIPs()
if err != nil {
return nil, err
}

ip4s := make([]string, 0)
for _, ip := range ips {
if net.ParseIP(ip).To4() != nil {
ip4s = append(ip4s, ip)
}
}

return ip4s, nil
}

func GetNetworkIPs() ([]string, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}

ips := make([]string, 0)
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
continue
}
for _, addr := range addrs {
switch v := addr.(type) {
case *net.IPNet:
ips = append(ips, v.IP.String())
case *net.IPAddr:
ips = append(ips, v.IP.String())
}
}
}

return ips, nil
}
12 changes: 12 additions & 0 deletions pkg/utils/json/json.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package josn

import "encoding/json"

func StructToJson(v interface{}) (string, error) {
data, err := json.MarshalIndent(v, "", " ")
if err != nil {
return "", err
}

return string(data), nil
}
43 changes: 43 additions & 0 deletions pkg/utils/parse/parse.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package parse

import "strconv"

func ParseBool(val string, defVal bool) bool {
_val, err := strconv.ParseBool(val)
if err != nil {
return defVal
}
return _val
}

func ParseInt(val string, defVal int) int {
_val, err := strconv.Atoi(val)
if err != nil {
return defVal
}
return _val
}

func ParseInt64(val string, defVal int64) int64 {
_val, err := strconv.ParseInt(val, 10, 64)
if err != nil {
return defVal
}
return _val
}

func ParseFloat64(val string, defVal float64) float64 {
_val, err := strconv.ParseFloat(val, 64)
if err != nil {
return defVal
}
return _val
}

func ParseUint(val string, defVal uint) uint {
_val, err := strconv.ParseUint(val, 10, 0)
if err != nil {
return defVal
}
return uint(_val)
}
Loading

0 comments on commit 56bac1e

Please sign in to comment.