Skip to content

Commit

Permalink
Merge pull request #5 from ArtisanCloud/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
Matrix-X authored May 29, 2022
2 parents 92bdd58 + 5012e96 commit 7c771e5
Show file tree
Hide file tree
Showing 12 changed files with 227 additions and 39 deletions.
54 changes: 54 additions & 0 deletions carbon/carbonPeriod.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"github.com/golang-module/carbon"
"reflect"
"time"
)

type CarbonPeriod struct {
Expand Down Expand Up @@ -31,6 +32,43 @@ func CreateCarbonPeriod() (p *CarbonPeriod) {
return p
}

func CreateCarbonPeriodWithCarbon(start *carbon.Carbon, end *carbon.Carbon) (p *CarbonPeriod) {

p = CreateCarbonPeriod()
p.startDatetime = start
p.endDatetime = end

return p
}

func CreateCarbonPeriodWithTime(start time.Time, end time.Time) (p *CarbonPeriod) {

startDate := carbon.Time2Carbon(start)
endDate := carbon.Time2Carbon(end)

p = CreateCarbonPeriod()
p.startDatetime = &startDate
p.endDatetime = &endDate

return p
}

func CreateCarbonPeriodWithString(start string, end string, format string) (p *CarbonPeriod) {

if format == "" {
format = DATETIME_FORMAT
}

startDate := carbon.ParseByFormat(start, format)
endDate := carbon.ParseByFormat(end, format)

p = CreateCarbonPeriod()
p.startDatetime = &startDate
p.endDatetime = &endDate

return p
}

func (period *CarbonPeriod) SetStartDate(date interface{}, inclusive interface{}) *CarbonPeriod {

//fmt.Println("set start datetime")
Expand Down Expand Up @@ -94,3 +132,19 @@ func (period *CarbonPeriod) calculateStart() int64 {
func (period *CarbonPeriod) calculateEnd() int64 {
return period.endDatetime.ToTimestamp()
}

func (period *CarbonPeriod) DiffInDays() int64 {

diffDays := period.startDatetime.DiffInDays(*period.endDatetime)

return diffDays

}

func (period *CarbonPeriod) IsDiffInDays(inDays int64) bool {

diffDays := period.startDatetime.DiffInDaysWithAbs(*period.endDatetime)

return diffDays <= inDays

}
28 changes: 28 additions & 0 deletions data/csv.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package data

import (
"bytes"
"encoding/csv"
"os"
)

func CSVEncode(arrayCSV [][]string) ([]byte, error) {

buffer := new(bytes.Buffer)
writer := csv.NewWriter(buffer)

err := writer.WriteAll(arrayCSV)

return buffer.Bytes(), err

}

func CSVEncodeToFile(arrayCSV [][]string, file *os.File) ( error) {

writer := csv.NewWriter(file)

err := writer.WriteAll(arrayCSV)

return err

}
28 changes: 28 additions & 0 deletions data/csv_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package data

import (
"os"
"testing"
)

func Test_CSVEncodeToFile(t *testing.T) {
var csvStruct [][]string
csvStruct = [][]string{
{"name", "address", "phone"},
{"Ram", "Tokyo", "1236524"},
{"Shaym", "Beijing", "8575675.484"},
}

csvFile, err := os.Create("csv_test.csv")
if err != nil {
t.Error(err)
}

defer csvFile.Close()

err = CSVEncodeToFile(csvStruct, csvFile)
if err != nil {
t.Error(err)
}

}
48 changes: 30 additions & 18 deletions http/drivers/gout/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func (client *Client) SendAsync(request contract.RequestInterface, options *obje

func (client *Client) PrepareRequest(method string, uri string, options *object.HashMap, outBody interface{}) (
df *dataflow.DataFlow,
queries *object.StringMap, headers interface{}, body interface{},
queries *object.StringMap, headers *object.HashMap, body interface{},
version string, debug bool, err error) {

(*options)[OPTION_SYNCHRONOUS] = true
Expand All @@ -63,10 +63,14 @@ func (client *Client) PrepareRequest(method string, uri string, options *object.
version = "1.1"

if (*options)["headers"] != nil {
headers = (*options)["headers"]
headers = (*options)["headers"].(*object.HashMap)
} else {
headers = &object.HashMap{}
}
if (*options)["body"] != nil {
body = (*options)["body"]
} else {
body = nil
}

if (*options)["version"] != nil {
Expand Down Expand Up @@ -124,7 +128,7 @@ func (client *Client) Request(method string, uri string, options *object.HashMap
return nil, err
}

df = client.applyOptions(df, options)
df = client.applyOptions(df, options, headers)

returnCode := http.StatusOK
df = df.
Expand Down Expand Up @@ -229,42 +233,50 @@ func (client *Client) prepareDefaults(options *object.HashMap) *object.HashMap {
return result
}

func (client *Client) applyOptions(r *dataflow.DataFlow, options *object.HashMap) *dataflow.DataFlow {
func (client *Client) applyOptions(r *dataflow.DataFlow, options *object.HashMap, headers *object.HashMap) *dataflow.DataFlow {

if (*options)["form_params"] != nil {
(*options)["body"], _ = object.StructToMap((*options)["form_params"])
(*options)["form_params"] = nil
var bodyData interface{}
switch (*options)["form_params"].(type) {
case string:
(*options)["body"], _ = (*options)["form_params"]
bodyData = (*options)["body"].(string)

r.SetBody(bodyData)
break

default:
(*options)["body"], _ = object.StructToMap((*options)["form_params"])
bodyData = (*options)["body"].(map[string]interface{})

r.SetJSON(bodyData)
}
(*options)["form_params"] = nil
(*options)["_conditional"] = &object.StringMap{
"Content-Type": "application/x-www-form-urlencoded",
}

bodyData := (*options)["body"].(map[string]interface{})
r.SetJSON(bodyData)

}

if (*options)["multipart"] != nil {
formData := gout.H{}

for _, media := range (*options)["multipart"].([]*object.HashMap) {
name := (*media)["name"].(string)

// load data from file
if (*media)["headers"] != nil {
value := (*media)["value"].(string)
//headers := (*media)["headers"].(string)
r.SetForm(gout.H{
name: gout.FormFile(value),
}).SetHeader(gout.H{})
headers = (*media)["headers"].(*object.HashMap)
formData[name] = gout.FormType{FileName: (*headers)["filename"].(string), File: gout.FormFile(value)}

} else
// load data from memory
{
value := (*media)["value"].([]byte)
r.SetForm(gout.H{
name: gout.FormMem(value),
})
formData[name] = gout.FormMem(value)
}
}

r.SetForm(formData)
}

return r
Expand Down
14 changes: 14 additions & 0 deletions http/drivers/gout/helper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package gout

import (
"github.com/ArtisanCloud/PowerLibs/object"
"github.com/guonaihong/gout"
)

func ConvertHashMapToGoutMap(hashMap *object.HashMap) gout.H{
gMap:=gout.H{}
for k,v :=range *hashMap{
gMap[k] = v
}
return gMap
}
6 changes: 3 additions & 3 deletions http/request/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (

type HttpRequest struct {
httpClient contract.ClientInterface
baseUri string
BaseURI string

Middlewares []interface{}
}
Expand Down Expand Up @@ -87,8 +87,8 @@ func (request *HttpRequest) PerformRequest(url string, method string, options *o
options = object.MergeHashMap(options, _defaults, &object.HashMap{"handler": request.GetMiddlewares()})

// use request baseUri as final
if request.baseUri != "" {
(*options)["base_uri"] = request.baseUri
if request.BaseURI != "" {
(*options)["base_uri"] = request.BaseURI
}

// use current http client driver to request
Expand Down
18 changes: 10 additions & 8 deletions object/attribute.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,17 +52,18 @@ func (attr *Attribute) SetAttribute(name string, value interface{}) *Attribute {
return attr
}

func (attr *Attribute) IsRequired(attributes interface{}) bool {
func (attr *Attribute) IsRequired(attribute string) bool {

has, _ := InHash(attributes, attr.GetRequired().(*HashMap))
requiredAttributes := attr.GetRequired()
has := ContainsString(requiredAttributes, attribute)
return has
}

func (attr *Attribute) GetRequired() interface{} {
func (attr *Attribute) GetRequired() []string {
if attr.Attributes["required"] != nil {
return attr.Attributes["required"]
return attr.Attributes["required"].([]string)
} else {
return HashMap{}
return []string{}
}
}

Expand Down Expand Up @@ -118,7 +119,7 @@ func (attr *Attribute) Has(key string) bool {

func (attr *Attribute) GetString(attribute string, defaultValue string) string {
strResult := attr.Get(attribute, defaultValue).(string)
if strResult==""{
if strResult == "" {
strResult = defaultValue
}
return strResult
Expand All @@ -132,8 +133,9 @@ func (attr *Attribute) Merge(attributes *HashMap) *Attribute {
}

func (attr *Attribute) CheckRequiredAttributes() error {
requiredAttributes := attr.GetRequired().(*HashMap)
for attribute, _ := range *requiredAttributes {

requiredAttributes := attr.GetRequired()
for _, attribute := range requiredAttributes {
if attr.GetAttribute(attribute, nil) == nil {
return errors.New(fmt.Sprintf("\"%s\" cannot be empty.", attribute))
}
Expand Down
11 changes: 4 additions & 7 deletions object/hashMap.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func MergeHashMap(toMap *HashMap, subMaps ...*HashMap) *HashMap {
for _, subMap := range subMaps {
if subMap != nil {
// 迭代每个HashMap
for k, v := range (*subMap) {
for k, v := range *subMap {
toV := (*toMap)[k]

// if the key is not exist in toMap
Expand All @@ -41,7 +41,6 @@ func MergeHashMap(toMap *HashMap, subMaps ...*HashMap) *HashMap {
return toMap
}


// ------------------------------- Replace --------------------------------------------
func ReplaceHashMapRecursive(toMap *HashMap, subMaps ...*HashMap) *HashMap {
if toMap == nil {
Expand Down Expand Up @@ -77,7 +76,7 @@ func HashMapToStringMap(obj *HashMap) (newMap *StringMap, err error) {

}

func StructToHashMapWithTag(obj interface{}, tag string) (newMap *HashMap, err error) {
func StructToHashMapWithXML(obj interface{}) (newMap *HashMap, err error) {

newMap = &HashMap{}

Expand All @@ -90,10 +89,8 @@ func StructToHashMapWithTag(obj interface{}, tag string) (newMap *HashMap, err e
for i := 0; i < e.NumField(); i++ {
field := e.Field(i).Interface()

key := e.Type().Field(i).Name
if tag != "" {
key = e.Type().Field(i).Tag.Get(tag)
}
key := e.Type().Field(i).Tag.Get("xml")

(*newMap)[key] = field

}
Expand Down
8 changes: 8 additions & 0 deletions object/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,11 @@ func JsonEncode(v interface{}) (string, error) {
func JsonDecode(data []byte, v interface{}) error {
return json.Unmarshal(data, v)
}

func JsonEscape(str string) (string, error) {
b, err := json.Marshal(str)
if err != nil {
return "", err
}
return string(b[1 : len(b)-1]), err
}
19 changes: 19 additions & 0 deletions object/object.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package object

import (
"bytes"
"encoding/gob"
"fmt"
"log"
)

func EncodeToBytes(p interface{}) []byte {
buf := bytes.Buffer{}
enc := gob.NewEncoder(&buf)
err := enc.Encode(p)
if err != nil {
log.Fatal(err)
}
fmt.Println("uncompressed size (bytes): ", len(buf.Bytes()))
return buf.Bytes()
}
11 changes: 11 additions & 0 deletions object/str.go
Original file line number Diff line number Diff line change
Expand Up @@ -285,3 +285,14 @@ func RandStringBytesMask(n int) string {

return string(b)
}


func ContainsString(s []string, str string) bool {
for _, v := range s {
if v == str {
return true
}
}

return false
}
Loading

0 comments on commit 7c771e5

Please sign in to comment.