diff --git a/carbon/carbonPeriod.go b/carbon/carbonPeriod.go index c638d39..6be65b8 100644 --- a/carbon/carbonPeriod.go +++ b/carbon/carbonPeriod.go @@ -4,6 +4,7 @@ import ( "errors" "github.com/golang-module/carbon" "reflect" + "time" ) type CarbonPeriod struct { @@ -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") @@ -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 + +} diff --git a/data/csv.go b/data/csv.go new file mode 100644 index 0000000..7af52fe --- /dev/null +++ b/data/csv.go @@ -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 + +} diff --git a/data/csv_test.go b/data/csv_test.go new file mode 100644 index 0000000..66dd0a2 --- /dev/null +++ b/data/csv_test.go @@ -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) + } + +} diff --git a/http/drivers/gout/client.go b/http/drivers/gout/client.go index d1020ce..85fc603 100644 --- a/http/drivers/gout/client.go +++ b/http/drivers/gout/client.go @@ -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 @@ -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 { @@ -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. @@ -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 diff --git a/http/drivers/gout/helper.go b/http/drivers/gout/helper.go new file mode 100644 index 0000000..3beeec8 --- /dev/null +++ b/http/drivers/gout/helper.go @@ -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 +} \ No newline at end of file diff --git a/http/request/request.go b/http/request/request.go index f090e5c..9198faa 100644 --- a/http/request/request.go +++ b/http/request/request.go @@ -14,7 +14,7 @@ import ( type HttpRequest struct { httpClient contract.ClientInterface - baseUri string + BaseURI string Middlewares []interface{} } @@ -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 diff --git a/object/attribute.go b/object/attribute.go index 3d3c7a2..8c67036 100644 --- a/object/attribute.go +++ b/object/attribute.go @@ -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{} } } @@ -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 @@ -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)) } diff --git a/object/hashMap.go b/object/hashMap.go index a223c7a..05fddc7 100644 --- a/object/hashMap.go +++ b/object/hashMap.go @@ -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 @@ -41,7 +41,6 @@ func MergeHashMap(toMap *HashMap, subMaps ...*HashMap) *HashMap { return toMap } - // ------------------------------- Replace -------------------------------------------- func ReplaceHashMapRecursive(toMap *HashMap, subMaps ...*HashMap) *HashMap { if toMap == nil { @@ -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{} @@ -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 } diff --git a/object/json.go b/object/json.go index 14e1936..30d73ca 100644 --- a/object/json.go +++ b/object/json.go @@ -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 +} diff --git a/object/object.go b/object/object.go new file mode 100644 index 0000000..8407ead --- /dev/null +++ b/object/object.go @@ -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() +} \ No newline at end of file diff --git a/object/str.go b/object/str.go index 7a31273..c263449 100644 --- a/object/str.go +++ b/object/str.go @@ -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 +} \ No newline at end of file diff --git a/object/stringMap.go b/object/stringMap.go index a9d15f4..aefc8ae 100644 --- a/object/stringMap.go +++ b/object/stringMap.go @@ -21,7 +21,7 @@ func MergeStringMap(toStringMap *StringMap, subStringMaps ...*StringMap) *String for k, v := range *subStringMap { toV := (*toStringMap)[k] // if the key is not exist in toMap - if toV == "" && v != ""{ + if toV == "" && v != "" { (*toStringMap)[k] = v } @@ -31,7 +31,6 @@ func MergeStringMap(toStringMap *StringMap, subStringMaps ...*StringMap) *String return toStringMap } - // ------------------------------- Replace -------------------------------------------- func ReplaceStringMapRecursive(toMap *StringMap, subMaps ...*StringMap) *StringMap { if toMap == nil { @@ -64,7 +63,7 @@ func StructToStringMapWithTag(obj interface{}, tag string) (newMap *StringMap, e newMap = &StringMap{} - if obj==nil{ + if obj == nil { return newMap, err } @@ -122,6 +121,22 @@ func GetJoinedWithKSort(params *StringMap) string { // ------------------------------- Search -------------------------------------------- +func InStringMap(val string, maps *StringMap) (exists bool, keys []string) { + exists = false + mapLen := len(*maps) + keys = make([]string, 0, mapLen) + + for k, v := range *maps { + if v == val { + keys = append(keys, k) + + exists = true + } + } + + return exists, keys +} + func GetStringMapKV(maps StringMap) (keys []string, values []string) { mapLen := len(maps) keys = make([]string, 0, mapLen)