Browse Source

代jiawei提交

master
巴林闲侠 2 years ago
parent
commit
efdf64addc
  1. 8
      gowork/.idea/.gitignore
  2. 9
      gowork/.idea/Web.iml
  3. 8
      gowork/.idea/modules.xml
  4. 2
      gowork/conf.ini
  5. 11
      gowork/src/main/main.go
  6. 3
      gowork/src/main/missionBoard-GO/conf.ini
  7. BIN
      gowork/src/main/missionBoard-GO/people.xls
  8. BIN
      gowork/src/main/missionBoard-GO/project.xls
  9. 156
      gowork/src/main/project/API.go
  10. 241
      gowork/src/main/project/DbServe.go
  11. 53
      gowork/src/main/project/downloadFile.go
  12. 128
      gowork/src/main/utils/db_utils.go
  13. 238
      gowork/src/main/utils/utils.go

8
gowork/.idea/.gitignore

@ -0,0 +1,8 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

9
gowork/.idea/Web.iml

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="Go" enabled="true" />
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

8
gowork/.idea/modules.xml

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/Web.iml" filepath="$PROJECT_DIR$/.idea/Web.iml" />
</modules>
</component>
</project>

2
gowork/conf.ini

@ -1,3 +1,3 @@
[Server] [Server]
type = postgres type = postgres
url1 = postgres://FashionAdmin:123456@10.8.30.36:5432/test url = postgres://FashionAdmin:123456@10.8.30.36:5432/test

11
gowork/src/main/main.go

@ -0,0 +1,11 @@
package main
import (
"Web/src/main/project"
)
func main() {
project.OpenDB()
project.Api()
select {}
}

3
gowork/src/main/missionBoard-GO/conf.ini

@ -0,0 +1,3 @@
[Server]
type = postgres
url = postgres://FashionAdmin:123456@10.8.30.36:5432/test

BIN
gowork/src/main/missionBoard-GO/people.xls

Binary file not shown.

BIN
gowork/src/main/missionBoard-GO/project.xls

Binary file not shown.

156
gowork/src/main/project/API.go

@ -0,0 +1,156 @@
package project
import (
"database/sql"
"fmt"
"github.com/gin-gonic/gin"
"github.com/goccy/go-json"
"io/ioutil"
"net/http"
)
func Api() {
e := gin.Default()
e.POST("/inProject", writeProject)
e.POST("/inPeople", writePeople)
e.POST("/inWait", writeWait)
e.POST("/outProject", readProject)
e.POST("/outPeople", readPeople)
e.POST("/outWait", readWait)
e.POST("/deleteDB", deleteDB)
e.GET("/downPeople", peopleMsg)
e.GET("/downProject", projectMsg)
e.Run(":8080")
}
func deleteDB(c *gin.Context) {
body, _ := ioutil.ReadAll(c.Request.Body)
if err := deleteDb(body); err != nil {
} else {
c.JSON(http.StatusOK, gin.H{
"result": "ok",
})
}
}
func readProject(c *gin.Context) {
var projects []Project
var project Project
var rows *sql.Rows
rows, err = db.Query(SearchProject)
if err != nil {
fmt.Printf("%s", err)
} else {
defer rows.Close()
for rows.Next() {
var pPeopleUint8 []uint8
if err = rows.Scan(&project.Name_project, &project.Build_time, &project.Publish_time, &pPeopleUint8, &project.Progress); err != nil {
fmt.Printf("%s", err)
} else {
ppStr := string(pPeopleUint8)
var pp []pPeople
err = json.Unmarshal([]byte(ppStr), &pp)
if err != nil {
fmt.Printf("%s", err)
return
}
project.Part_people = pp
projects = append(projects, project)
}
}
c.JSON(http.StatusOK, gin.H{
"total": len(projects),
"projects": projects})
}
}
func readPeople(c *gin.Context) {
var projects []People
var project People
var rows *sql.Rows
rows, err = db.Query(SearchPeople)
if err != nil {
fmt.Printf("%s", err)
} else {
defer rows.Close()
for rows.Next() {
var WorkUint8 []uint8
if err = rows.Scan(&project.Name_people, &project.Post_people, &WorkUint8); err != nil {
fmt.Printf("%s", err)
} else {
workStr := string(WorkUint8)
var work []Work
err = json.Unmarshal([]byte(workStr), &work)
if err != nil {
fmt.Printf("%s", err)
return
}
project.Work = work
projects = append(projects, project)
}
}
c.JSON(http.StatusOK, gin.H{
"total": len(projects),
"projects": projects})
}
}
func readWait(c *gin.Context) {
var projects []Wait
var project Wait
var rows *sql.Rows
rows, err = db.Query(SearchWait)
if err != nil {
fmt.Printf("%s", err)
} else {
defer rows.Close()
for rows.Next() {
if err = rows.Scan(&project.Name_project, &project.From_project, &project.Contacts, &project.Progress); err != nil {
fmt.Printf("%s", err)
} else {
projects = append(projects, project)
}
}
c.JSON(http.StatusOK, gin.H{
"total": len(projects),
"projects": projects})
}
}
func writeProject(c *gin.Context) {
body, _ := ioutil.ReadAll(c.Request.Body)
if err := ProjectInDB(body); err != nil {
} else {
c.JSON(http.StatusOK, gin.H{
"result": "ok",
})
}
}
func writePeople(c *gin.Context) {
body, _ := ioutil.ReadAll(c.Request.Body)
if err := PeopleInDB(body); err != nil {
} else {
c.JSON(http.StatusOK, gin.H{
"result": "ok",
})
}
}
func writeWait(c *gin.Context) {
body, _ := ioutil.ReadAll(c.Request.Body)
if err := WaitInDB(body); err != nil {
} else {
c.JSON(http.StatusOK, gin.H{
"result": "ok",
})
}
}

241
gowork/src/main/project/DbServe.go

@ -0,0 +1,241 @@
package project
import (
"Web/src/main/utils"
"database/sql"
"encoding/json"
"fmt"
_ "github.com/lib/pq"
"sync"
)
var db *sql.DB
var err error
var wg sync.WaitGroup
var mt sync.Mutex
func OpenDB() {
//conf, err := ini.Load("conf.ini")
//if err != nil {
// fmt.Printf("%s", err)
//}
//
//for _, v := range conf.Sections() {
// fmt.Println(v.KeyStrings())
//}
utils.IniInit()
url := utils.GIniParser.GetString("Server", "url")
dbType := utils.GIniParser.GetString("Server", "type")
//dbType := "postgres"
//dbType := "postgres://postgres:postgres@10.8.30.156:5432/Anxinyun0808?sslmode=disable"
//url := "postgres://FashionAdmin:123456@10.8.30.36:5432/test"
if db, err = sql.Open(dbType, url); err != nil {
fmt.Printf("%s", err)
return
} else {
err := db.Ping()
if err != nil {
fmt.Printf("%s", err)
}
println("Open db success")
}
}
func deleteDb(str []byte) error {
var body delete
if err = json.Unmarshal(str, &body); err != nil {
fmt.Printf("%s", err)
return err
} else {
tableName := body.Table_name
var k1 string
var k2 string
switch tableName {
case "test_people":
k1 = "name_people"
k2 = "post_people"
case "test_prpject":
k1 = "name_project"
k2 = "post_progress"
case "test_waiting":
k1 = "name_project"
k2 = "progress"
}
v1 := body.Delete
v2 := body.Delete_state
deleteSQL := fmt.Sprintf("DELETE FROM \"%v\" WHERE %v = '%v' AND %v = '%v'", tableName, k1, v1, k2, v2)
_, err = db.Exec(deleteSQL)
if err != nil {
fmt.Printf("%s", err)
return err
}
return nil
}
}
func ProjectInDB(str []byte) error {
var bodys []Project
if err = json.Unmarshal(str, &bodys); err != nil {
return err
} else {
var Err chan error
for _, body := range bodys {
wg.Add(1)
go func(body Project) {
mt.Lock()
defer mt.Unlock()
defer wg.Done()
var bytePeople []byte
bytePeople, err = json.Marshal(body.Part_people)
if err != nil {
fmt.Printf("%s", err)
}
peopleSQL := fmt.Sprintf(
"DO $$ BEGIN\n"+
"IF NOT EXISTS ( SELECT * FROM test_project WHERE name_project = '%v' ) THEN\n"+
"INSERT INTO test_project (name_project, build_time, publish_time, part_people, progress )VALUES( '%v', '%v', '%v', '%v', '%v' );\n"+
"ELSE\n"+
"UPDATE test_project SET build_time = '%v',publish_time = '%v',part_people = '%v',progress = '%v' WHERE name_project = '%v';\n"+
"END IF;\nEND $$",
body.Name_project, body.Name_project, body.Build_time, body.Publish_time, string(bytePeople), body.Progress, body.Build_time, body.Publish_time, string(bytePeople), body.Progress, body.Name_project)
//var result sql.Result
_, err = db.Exec(peopleSQL)
if err != nil {
fmt.Printf("%s", err)
}
if err != nil {
Err <- err
}
}(body)
}
wg.Wait()
if len(Err) != 0 {
return <-Err
}
return nil
}
}
func PeopleInDB(str []byte) error {
var bodys []People
if err = json.Unmarshal(str, &bodys); err != nil {
return err
} else {
var Err chan error
for _, body := range bodys {
wg.Add(1)
go func(body People) {
mt.Lock()
defer mt.Unlock()
defer wg.Done()
var byteWork []byte
byteWork, err = json.Marshal(body.Work)
if err != nil {
fmt.Printf("%s", err)
}
peopleSQL := fmt.Sprintf(
"DO\n$$\nBEGIN \n"+
"IF NOT EXISTS (select * FROM test_people WHERE name_people = '%v')\nTHEN\n"+
"INSERT INTO test_people (name_people,post_people,work)VALUES('%v','%v','%v');\n"+
"ELSE\n"+
"UPDATE test_people SET post_people ='%v' ,work= '%v' WHERE name_people = '%v';\n"+
"end if;\nEND\n$$",
body.Name_people, body.Name_people, body.Post_people, string(byteWork), body.Post_people, string(byteWork), body.Name_people)
//var result sql.Result
_, err = db.Exec(peopleSQL)
if err != nil {
fmt.Printf("%s", err)
}
if err != nil {
Err <- err
}
}(body)
}
wg.Wait()
if len(Err) != 0 {
return <-Err
}
return nil
}
}
func WaitInDB(str []byte) error {
var bodys []Wait
if err = json.Unmarshal(str, &bodys); err != nil {
return err
} else {
var Err chan error
for _, body := range bodys {
wg.Add(1)
go func(body Wait) {
mt.Lock()
defer mt.Unlock()
defer wg.Done()
peopleSQL := fmt.Sprintf(""+
"DO $$ BEGIN\n"+
"IF NOT EXISTS ( SELECT * FROM test_waiting WHERE name_project = '%v' ) THEN\n"+
"INSERT INTO test_waiting (name_project, from_project, contacts, progress)VALUES( '%v', '%v', '%v', '%v' );\n"+
"ELSE\n"+
"UPDATE test_waiting SET from_project = '%v',contacts = '%v',progress = '%v' WHERE name_project = '%v';\n"+
"END IF;\nEND $$",
body.Name_project, body.Name_project, body.From_project, body.Contacts, body.Progress, body.From_project, body.Contacts, body.Progress, body.Name_project)
//var result sql.Result
_, err = db.Exec(peopleSQL)
if err != nil {
fmt.Printf("%s", err)
}
if err != nil {
Err <- err
}
}(body)
}
wg.Wait()
if len(Err) != 0 {
return <-Err
}
return nil
}
}
type delete struct {
Table_name string `json:"table_name"`
Delete string `json:"delete"`
Delete_state string `json:"delete_state"`
}
type Project struct {
Name_project string `json:"name_project"`
Build_time string `json:"build_time"`
Publish_time string `json:"publish_time"`
Part_people []pPeople `json:"part_people"`
Progress string `json:"progress"`
}
type pPeople struct {
Name_people string `json:"name_people"`
}
type People struct {
Name_people string `json:"name_people"`
Post_people string `json:"post_people"`
Work []Work `json:"work"`
}
type Work struct {
Time string `json:"time"`
Project string `json:"project"`
}
type Wait struct {
Name_project string `json:"name_project"`
From_project string `json:"from_project"`
Contacts string `json:"contacts"`
Progress string `json:"progress"`
}
const SearchProject = `SELECT * FROM "test_project"`
const SearchPeople = `SELECT * FROM "test_people"`
const SearchWait = `SELECT * FROM "test_waiting"`

53
gowork/src/main/project/downloadFile.go

@ -0,0 +1,53 @@
package project
import (
"fmt"
"github.com/gin-gonic/gin"
"io"
"net/http"
"os"
)
func peopleMsg(c *gin.Context) {
file, err := os.Open("people.xls")
if err != nil {
c.JSON(http.StatusNotFound, gin.H{
"result": "文件加载失败" + fmt.Sprintf("%s", err),
})
fmt.Printf("%s", err)
return
}
defer file.Close()
c.Writer.Header().Add("Content-Type", "application/octet-stream")
_, err = io.Copy(c.Writer, file)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{
"result": "文件加载失败" + fmt.Sprintf("%s", err),
})
fmt.Printf("%s", err)
return
}
}
func projectMsg(c *gin.Context) {
file, err := os.Open("project.xls")
if err != nil {
c.JSON(http.StatusNotFound, gin.H{
"result": "文件加载失败" + fmt.Sprintf("%s", err),
})
fmt.Printf("%s", err)
return
}
defer file.Close()
c.Writer.Header().Add("Content-Type", "application/octet-stream")
_, err = io.Copy(c.Writer, file)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{
"result": "文件加载失败" + fmt.Sprintf("%s", err),
})
fmt.Printf("%s", err)
return
}
}

128
gowork/src/main/utils/db_utils.go

@ -0,0 +1,128 @@
package utils
import (
"database/sql"
"time"
)
// closeRows 关闭查询结果
func CloseRows(rows *sql.Rows) {
if rows != nil {
rows.Close()
}
}
// ScanRow: 识别空串
func ScanRows(rows *sql.Rows, dest ...interface{}) {
ds := make([]interface{}, len(dest))
for i, d := range dest {
switch d.(type) {
case *int8, *int, *int16, *int32, *int64, *uint, *uint8, *uint16, *uint32, *uint64:
ds[i] = new(sql.NullInt64)
case *float32, *float64:
ds[i] = new(sql.NullFloat64)
case *bool:
ds[i] = new(sql.NullBool)
default:
ds[i] = new(sql.NullString) // 替换为 NullString
}
}
err := rows.Scan(ds...)
if err != nil {
//log.Error("scan error: %s", err.Error())
return
}
for i, d := range dest {
switch di := d.(type) {
case *uint8:
switch iv := ds[i].(type) {
case *sql.NullInt64:
*di = uint8(iv.Int64)
}
case *int8:
switch iv := ds[i].(type) {
case *sql.NullInt64:
*di = int8(iv.Int64)
}
case *int:
switch iv := ds[i].(type) {
case *sql.NullInt64:
*di = int(iv.Int64)
}
case *uint:
switch iv := ds[i].(type) {
case *sql.NullInt64:
*di = uint(iv.Int64)
}
case *int32:
switch iv := ds[i].(type) {
case *sql.NullInt64:
*di = int32(iv.Int64)
}
case *uint32:
switch iv := ds[i].(type) {
case *sql.NullInt64:
*di = uint32(iv.Int64)
}
case *int64:
switch iv := ds[i].(type) {
case *sql.NullInt64:
*di = int64(iv.Int64)
}
case *uint64:
switch iv := ds[i].(type) {
case *sql.NullInt64:
*di = uint64(iv.Int64)
}
case *float32:
switch fv := ds[i].(type) {
case *sql.NullFloat64:
*di = float32(fv.Float64)
}
case *float64:
switch fv := ds[i].(type) {
case *sql.NullFloat64:
*di = fv.Float64
}
case *bool:
switch bv := ds[i].(type) {
case *sql.NullBool:
*di = bv.Bool
}
case *string:
switch sv := ds[i].(type) {
case *sql.NullString:
*di = sv.String
}
case *time.Time:
switch sv := ds[i].(type) {
case *sql.NullString: // cast to string
s := sv.String
if !sv.Valid || IsEmpty(s) {
*di = time.Time{}
} else {
*di, _ = time.Parse(time.RFC3339, s) // "2017-08-08T11:39:02+08:00"
}
}
default:
{
// 不支持的格式.
//log.Warn("[ds.scanRows]: Unsupport type: %v", reflect.TypeOf(d))
}
}
}
}
// joinStr: [s1,s2,s3] => "'s1','s2','s3'". 若 si中有 ", 则替换为 \"
func joinStr(ss []string) string {
var si string
var count = len(ss)
for i, s := range ss {
// s = strings.Replace(s, "\"", "\\\"", -1)
si += "'" + s + "'"
if i != count-1 {
si += ","
}
}
return si
}

238
gowork/src/main/utils/utils.go

@ -0,0 +1,238 @@
package utils
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/satori/go.uuid"
"gopkg.in/ini.v1"
"os"
"strconv"
"strings"
)
type IniParser struct {
conf_reader *ini.File // config reader
}
type IniParserError struct {
error_info string
}
var GIniParser *IniParser
func IniInit() {
GIniParser = &IniParser{}
if _, err := os.Stat("conf.ini"); os.IsNotExist(err) {
if _, err := os.Stat("../conf.ini"); os.IsNotExist(err) {
// run in test dir
_ = GIniParser.Load("../../conf.ini")
} else {
// run in craw dir
_ = GIniParser.Load("../conf.ini")
}
} else {
// run in src dir
_ = GIniParser.Load("conf.ini")
}
}
func (e *IniParserError) Error() string { return e.error_info }
func (this *IniParser) Load(config_file_name string) error {
conf, err := ini.Load(config_file_name)
if err != nil {
this.conf_reader = nil
return err
}
this.conf_reader = conf
return nil
}
func (this *IniParser) GetString(section string, key string) string {
if this.conf_reader == nil {
return ""
}
s := this.conf_reader.Section(section)
if s == nil {
return ""
}
return s.Key(key).String()
}
func (this *IniParser) GetStringDefault(section string, key string, defaultVal string) string {
if this.conf_reader == nil {
return ""
}
s := this.conf_reader.Section(section)
if s == nil {
return defaultVal
}
ret := s.Key(key).String()
if ret == "" {
return defaultVal
}
return ret
}
func (this *IniParser) GetInt32(section string, key string) int32 {
if this.conf_reader == nil {
return 0
}
s := this.conf_reader.Section(section)
if s == nil {
return 0
}
value_int, _ := s.Key(key).Int()
return int32(value_int)
}
func (this *IniParser) GetUint32(section string, key string) uint32 {
if this.conf_reader == nil {
return 0
}
s := this.conf_reader.Section(section)
if s == nil {
return 0
}
value_int, _ := s.Key(key).Uint()
return uint32(value_int)
}
func (this *IniParser) GetInt64(section string, key string) int64 {
if this.conf_reader == nil {
return 0
}
s := this.conf_reader.Section(section)
if s == nil {
return 0
}
value_int, _ := s.Key(key).Int64()
return value_int
}
func (this *IniParser) GetUint64(section string, key string) uint64 {
if this.conf_reader == nil {
return 0
}
s := this.conf_reader.Section(section)
if s == nil {
return 0
}
value_int, _ := s.Key(key).Uint64()
return value_int
}
func (this *IniParser) GetFloat32(section string, key string) float32 {
if this.conf_reader == nil {
return 0
}
s := this.conf_reader.Section(section)
if s == nil {
return 0
}
value_float, _ := s.Key(key).Float64()
return float32(value_float)
}
func (this *IniParser) GetFloat64(section string, key string) float64 {
if this.conf_reader == nil {
return 0
}
s := this.conf_reader.Section(section)
if s == nil {
return 0
}
value_float, _ := s.Key(key).Float64()
return value_float
}
func NewUUIDV4() string {
return uuid.NewV4().String()
}
func Md5(str string) string {
h := md5.New()
h.Write([]byte(str))
return hex.EncodeToString(h.Sum(nil))
}
// ToBytes AA555A0000000000 => AA 55 5A 00 ....
func ToBytes(s string) []byte {
s = strings.Replace(s, " ", "", -1)
blen := len(s) / 2
bytes := make([]byte, blen)
for i := 0; i < blen; i++ {
v, _ := strconv.ParseUint(s[i*2:i*2+2], 16, 8) //16位, 一个byte
bytes[i] = byte(v)
}
return bytes
}
// ToHexStr : [0xAA,0x55,0x5A,0x00] => "AA555A00"
func ToHexStr(buff []byte) string {
return hex.EncodeToString(buff)
}
// ToJSON 将一个json串解码为匿名结构, 有错误时返回nil
func ToJSON(s string) interface{} {
var v interface{}
if err := json.Unmarshal([]byte(s), &v); err == nil {
return v
}
return nil
}
// ToJSONStr 编码一个匿名结构为 json 串, 有错误时返回 ""
func ToJSONStr(d interface{}) string {
if buff, err := json.Marshal(d); err == nil {
return string(buff)
}
return ""
}
// ToJSONBytes 编码一个匿名结构为 json 串, 有错误时返回 ""
func ToJSONBytes(d interface{}) []byte {
if buff, err := json.Marshal(d); err == nil {
return buff
}
return nil
}
// IsNotEmpty 判定字串非空(空格)
func IsNotEmpty(s string) bool {
return strings.TrimSpace(s) != ""
}
// IsEmpty 判定字串为空(或空格)
func IsEmpty(s string) bool {
return strings.TrimSpace(s) == ""
}
// TrimPrec 剪切浮点精度为制定位数
func TrimPrec(v float64, prec int) float64 {
pf := fmt.Sprintf("%%0.%df", prec)
if nv, err := strconv.ParseFloat(fmt.Sprintf(pf, v), 64); err == nil {
return nv
}
return v
}
Loading…
Cancel
Save