Skip to content

Commit

Permalink
feat: add image api
Browse files Browse the repository at this point in the history
refactor: project list refactor
  • Loading branch information
chancel.yang committed Jun 13, 2022
1 parent 1ec01c9 commit 9f058c0
Show file tree
Hide file tree
Showing 7 changed files with 185 additions and 89 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
.vscode
go-tools-api
dist/
.goreleaser.yml
*.log
conf/app.conf
6 changes: 6 additions & 0 deletions conf/app.conf.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[general]
host = 0.0.0.0
port = 8042

[image]
path = /home/chancel/images
92 changes: 92 additions & 0 deletions controllers/api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package controllers

import (
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"os"
"path/filepath"

"go-tools-api/models"

"github.com/labstack/echo/v4"
)

var ImagePath string

// Handler
func IP(c echo.Context) error {
r := &models.Response{
Status: 1,
Msg: "查询成功",
Data: map[string]interface{}{
"ip": c.RealIP(),
},
}
return c.JSON(http.StatusOK, r)
}

func Telegram(c echo.Context) (err error) {
t := new(models.Telegram)
if err = c.Bind(t); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
url := fmt.Sprintf("https://api.telegram.org/bot%s/SendMessage?text=%s&chat_id=%s&parse_mode=MarkdownV2", t.ApiKey, t.MsgText, t.ChatID)
resp, gErr := http.Get(url)
if gErr != nil {
r := &models.Response{
Status: 0,
Msg: gErr.Error(),
Data: nil,
}
return c.JSON(http.StatusOK, r)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var telegramResponse models.TelegramResponse
json.Unmarshal(body, &telegramResponse)
if !telegramResponse.Ok {
r := &models.Response{
Status: 0,
Msg: telegramResponse.Description,
Data: telegramResponse.Result,
}
return c.JSON(http.StatusOK, r)
}
r := &models.Response{
Status: 1,
Msg: "消息发送成功",
Data: telegramResponse.Result,
}
return c.JSON(http.StatusOK, r)
}

var imageIndex int

func Image(c echo.Context) error {
var files []string

err := filepath.Walk(ImagePath, func(path string, info os.FileInfo, err error) error {
files = append(files, path)
return nil
})
if err != nil || len(files) < 2 {
r := &models.Response{
Status: 0,
Msg: "Get image error",
Data: nil,
}
return c.JSON(http.StatusOK, r)
}
for {
randomIndex := rand.Intn(len(files) - 1)
if randomIndex != imageIndex {
imageIndex = randomIndex
break
}
}
return c.File(files[imageIndex])

}
11 changes: 10 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,13 @@ module go-tools-api

go 1.15

require github.com/labstack/echo/v4 v4.6.1
require (
github.com/go-ini/ini v1.66.6
github.com/labstack/echo/v4 v4.7.2
github.com/labstack/gommon v0.3.1
github.com/mattn/go-colorable v0.1.12 // indirect
golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e // indirect
golang.org/x/sys v0.0.0-20220608164250-635b8c9b7f68 // indirect
golang.org/x/time v0.0.0-20220609170525-579cf78fd858 // indirect
gopkg.in/yaml.v2 v2.2.2 // indirect
)
21 changes: 21 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-ini/ini v1.66.6 h1:h6k2Bb0HWS/BXXHCXj4QHjxPmlIU4NK+7MuLp9SD+4k=
github.com/go-ini/ini v1.66.6/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/labstack/echo v1.4.4 h1:1bEiBNeGSUKxcPDGfZ/7IgdhJJZx8wV/pICJh4W2NJI=
github.com/labstack/echo v3.3.10+incompatible h1:pGRcYk231ExFAyoAjAfD85kQzRJCRI8bbnE7CX5OEgg=
github.com/labstack/echo/v4 v4.6.1 h1:OMVsrnNFzYlGSdaiYGHbgWQnr+JM7NG+B9suCPie14M=
github.com/labstack/echo/v4 v4.6.1/go.mod h1:RnjgMWNDB9g/HucVWhQYNQP9PvbYf6adqftqryo7s9k=
github.com/labstack/echo/v4 v4.7.2 h1:Kv2/p8OaQ+M6Ex4eGimg9b9e6icoxA42JSlOR3msKtI=
github.com/labstack/echo/v4 v4.7.2/go.mod h1:xkCDAdFCIf8jsFQ5NnbK7oqaF/yU1A1X20Ltm0OvSks=
github.com/labstack/gommon v0.3.0 h1:JEeO0bvc78PKdyHxloTKiF8BD5iGrH8T6MSeGvSgob0=
github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k=
github.com/labstack/gommon v0.3.1 h1:OomWaJXm7xR6L1HmEtGyQf26TEn7V6X88mktX9kee9o=
Expand All @@ -21,8 +26,10 @@ github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2y
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
Expand All @@ -34,12 +41,18 @@ golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 h1:HWj/xjIHfjYU5nVXpTM0s3
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20211202192323-5770296d904e h1:MUP6MR3rJ7Gk9LEia0LP2ytiH6MuCfs7qYz+47jGdD8=
golang.org/x/crypto v0.0.0-20211202192323-5770296d904e/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e h1:T8NU3HyQ8ClP4SEE+KbFlg6n0NhuTsN4MyznaarGsZM=
golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210913180222-943fd674d43e h1:+b/22bPvDYt4NPDcy4xAGCmON713ONAWFeY3Z7I3tR8=
golang.org/x/net v0.0.0-20210913180222-943fd674d43e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 h1:CIJ76btIcR3eFI5EgSo6k1qKw9KJexJuRLI9G7Hp5wE=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211203184738-4852103109b8 h1:PFkPt/jI9Del3hmFplBtRp8tDhSRpFu7CyRs7VmEC0M=
golang.org/x/net v0.0.0-20211203184738-4852103109b8/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220607020251-c690dde0001d h1:4SFsTMi4UahlKoloni7L4eYzhFRifURQLw+yv0QDCx8=
golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
Expand All @@ -54,7 +67,11 @@ golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211204120058-94396e421777 h1:QAkhGVjOxMa+n4mlsAWeAU+BMZmimQAaNiMu+iUi94E=
golang.org/x/sys v0.0.0-20211204120058-94396e421777/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220608164250-635b8c9b7f68 h1:z8Hj/bl9cOV2grsOpEaQFUaly0JWN3i97mo3jXKJNp0=
golang.org/x/sys v0.0.0-20220608164250-635b8c9b7f68/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
Expand All @@ -63,8 +80,12 @@ golang.org/x/time v0.0.0-20201208040808-7e3f01d25324 h1:Hir2P/De0WpUhtrKGGjvSb2Y
golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11 h1:GZokNIeuVkl3aZHJchRrr13WCsols02MLUcz1U9is6M=
golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20220609170525-579cf78fd858 h1:Dpdu/EMxGMFgq0CeYMh4fazTD2vtlZRYE7wyynxJb9U=
golang.org/x/time v0.0.0-20220609170525-579cf78fd858/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
120 changes: 32 additions & 88 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,123 +1,67 @@
package main

import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"go-tools-api/controllers"
"log"
"net/http"
"os"

"github.com/go-ini/ini"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)

type Response struct {
Status int `json:"status"`
Msg string `json:"msg"`
Data map[string]interface{} `json:"data"`
}

type Telegram struct {
ApiKey string `json:"apiKey"`
ChatID string `json:"chatId"`
MsgText string `json:"msgText"`
}

type TelegramResponse struct {
Ok bool `json:"ok"`
Result map[string]interface{} `json:"result"`
ErrorCode int `json:"error_code"`
Description string `json:"description"`
}

var (
h bool
host string
port int
)

func init() {
flag.BoolVar(&h, "h", false, "this help")
flag.StringVar(&host, "host", "127.0.0.1", "listen host")
flag.IntVar(&port, "port", 1323, "listen port")
}

func main() {
h := flag.Bool("h", false, "--help")
conf := flag.String("c", "app.conf", "app.conf path")
flag.Parse()

if h {
if *h {
flag.Usage()
}
_, err := os.Stat(*conf)
if err != nil {
fmt.Println("app.conf not found")
os.Exit(-1)
}

cfg, err := ini.Load(*conf)
if err != nil {
log.Fatal("Fail to read file: ", err)
os.Exit(-1)
}

host := cfg.Section("general").Key("host").String()
port, err := cfg.Section("general").Key("port").Int()
if err != nil {
log.Fatal("Read conf error: ", err)
os.Exit(-1)
}

// Echo instance
e := echo.New()

// Middleware
e.Use(middleware.Logger())
fileWriter, err := os.OpenFile("ta.log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755)
fileWriter, err := os.OpenFile("go-tools-api-running.log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755)
if err != nil {
log.Fatalf("create file ta.log failed:%v", err.Error())
log.Fatalf("create file go-tools-api-running.log failed:%v", err.Error())
}
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
Format: "${time_rfc3339} - ${remote_ip} - ${method} - ${status} - ${uri}\n",
Output: fileWriter,
}))
e.Use(middleware.Recover())

controllers.ImagePath = cfg.Section("image").Key("path").String()

// Routes
e.GET("/rest/api/v1/ip", ip)
e.GET("/rest/api/v1/ip", controllers.IP)

e.POST("/rest/api/v1/telegram", controllers.Telegram)

e.POST("/rest/api/v1/telegram", telegram)
e.GET("/rest/api/v1/image", controllers.Image)

// Start server
e.Logger.Fatal(e.Start(fmt.Sprintf("%s:%d", host, port)))
}

// Handler
func ip(c echo.Context) error {
r := &Response{
Status: 1,
Msg: "查询成功",
Data: map[string]interface{}{
"ip": c.RealIP(),
},
}
return c.JSON(http.StatusOK, r)
}

func telegram(c echo.Context) (err error) {
t := new(Telegram)
if err = c.Bind(t); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
url := fmt.Sprintf("https://api.telegram.org/bot%s/SendMessage?text=%s&chat_id=%s&parse_mode=MarkdownV2", t.ApiKey, t.MsgText, t.ChatID)
resp, gErr := http.Get(url)
if gErr != nil {
r := &Response{
Status: 0,
Msg: gErr.Error(),
Data: nil,
}
return c.JSON(http.StatusOK, r)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var telegramResponse TelegramResponse
json.Unmarshal(body, &telegramResponse)
if !telegramResponse.Ok {
r := &Response{
Status: 0,
Msg: telegramResponse.Description,
Data: telegramResponse.Result,
}
return c.JSON(http.StatusOK, r)
}
r := &Response{
Status: 1,
Msg: "消息发送成功",
Data: telegramResponse.Result,
}
return c.JSON(http.StatusOK, r)

}
20 changes: 20 additions & 0 deletions models/http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package models

type Response struct {
Status int `json:"status"`
Msg string `json:"msg"`
Data map[string]interface{} `json:"data"`
}

type Telegram struct {
ApiKey string `json:"apiKey"`
ChatID string `json:"chatId"`
MsgText string `json:"msgText"`
}

type TelegramResponse struct {
Ok bool `json:"ok"`
Result map[string]interface{} `json:"result"`
ErrorCode int `json:"error_code"`
Description string `json:"description"`
}

0 comments on commit 9f058c0

Please sign in to comment.