diff --git a/const/const.go b/const/const.go new file mode 100644 index 0000000..96a9bec --- /dev/null +++ b/const/const.go @@ -0,0 +1,21 @@ +package _const + +var RespCode map[int]string + +const ( + RESP_ERR_COMON = 101 + RESP_ERR_OK = 0 +) + +func init() { + RespCode[RESP_ERR_OK] = "OK" + RespCode[RESP_ERR_COMON] = "Err" +} +func M(key int) string{ + v,ok := RespCode[key] + if ok{ + return v + }else { + return "" + } +} \ No newline at end of file diff --git a/controller/hanlder.go b/controller/hanlder.go index 012c96b..a2d42f1 100644 --- a/controller/hanlder.go +++ b/controller/hanlder.go @@ -74,14 +74,29 @@ func Auth(c *gin.Context) { // @Produce json // @Param q query string false "name search by q" // @Success 200 {array} util.RespBase -// @Failure 400 {object} util.RespBase -// @Failure 404 {object} util.RespBase -// @Failure 500 {object} util.RespBase // @Router /accounts [get] func SetUser(c *gin.Context){ - + var req model.Users + var resp RespBase + resp.Msg = "操作失败" + resp.Status = 20 + defer func() { + c.JSON(200,resp) + }() + e := c.BindJSON(&req) + if nil != e{ + logs.Error(e.Error()) + return + } + } func DelUser(c *gin.Context){ + var resp RespBase + resp.Msg = "操作失败" + resp.Status = 20 + defer func() { + c.JSON(200,resp) + }() } diff --git a/vendor/cloud.google.com/go/civil/LICENSE b/vendor/cloud.google.com/go/civil/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/vendor/cloud.google.com/go/civil/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/cloud.google.com/go/civil/civil.go b/vendor/cloud.google.com/go/civil/civil.go new file mode 100644 index 0000000..1cb2675 --- /dev/null +++ b/vendor/cloud.google.com/go/civil/civil.go @@ -0,0 +1,277 @@ +// Copyright 2016 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package civil implements types for civil time, a time-zone-independent +// representation of time that follows the rules of the proleptic +// Gregorian calendar with exactly 24-hour days, 60-minute hours, and 60-second +// minutes. +// +// Because they lack location information, these types do not represent unique +// moments or intervals of time. Use time.Time for that purpose. +package civil + +import ( + "fmt" + "time" +) + +// A Date represents a date (year, month, day). +// +// This type does not include location information, and therefore does not +// describe a unique 24-hour timespan. +type Date struct { + Year int // Year (e.g., 2014). + Month time.Month // Month of the year (January = 1, ...). + Day int // Day of the month, starting at 1. +} + +// DateOf returns the Date in which a time occurs in that time's location. +func DateOf(t time.Time) Date { + var d Date + d.Year, d.Month, d.Day = t.Date() + return d +} + +// ParseDate parses a string in RFC3339 full-date format and returns the date value it represents. +func ParseDate(s string) (Date, error) { + t, err := time.Parse("2006-01-02", s) + if err != nil { + return Date{}, err + } + return DateOf(t), nil +} + +// String returns the date in RFC3339 full-date format. +func (d Date) String() string { + return fmt.Sprintf("%04d-%02d-%02d", d.Year, d.Month, d.Day) +} + +// IsValid reports whether the date is valid. +func (d Date) IsValid() bool { + return DateOf(d.In(time.UTC)) == d +} + +// In returns the time corresponding to time 00:00:00 of the date in the location. +// +// In is always consistent with time.Date, even when time.Date returns a time +// on a different day. For example, if loc is America/Indiana/Vincennes, then both +// time.Date(1955, time.May, 1, 0, 0, 0, 0, loc) +// and +// civil.Date{Year: 1955, Month: time.May, Day: 1}.In(loc) +// return 23:00:00 on April 30, 1955. +// +// In panics if loc is nil. +func (d Date) In(loc *time.Location) time.Time { + return time.Date(d.Year, d.Month, d.Day, 0, 0, 0, 0, loc) +} + +// AddDays returns the date that is n days in the future. +// n can also be negative to go into the past. +func (d Date) AddDays(n int) Date { + return DateOf(d.In(time.UTC).AddDate(0, 0, n)) +} + +// DaysSince returns the signed number of days between the date and s, not including the end day. +// This is the inverse operation to AddDays. +func (d Date) DaysSince(s Date) (days int) { + // We convert to Unix time so we do not have to worry about leap seconds: + // Unix time increases by exactly 86400 seconds per day. + deltaUnix := d.In(time.UTC).Unix() - s.In(time.UTC).Unix() + return int(deltaUnix / 86400) +} + +// Before reports whether d1 occurs before d2. +func (d1 Date) Before(d2 Date) bool { + if d1.Year != d2.Year { + return d1.Year < d2.Year + } + if d1.Month != d2.Month { + return d1.Month < d2.Month + } + return d1.Day < d2.Day +} + +// After reports whether d1 occurs after d2. +func (d1 Date) After(d2 Date) bool { + return d2.Before(d1) +} + +// MarshalText implements the encoding.TextMarshaler interface. +// The output is the result of d.String(). +func (d Date) MarshalText() ([]byte, error) { + return []byte(d.String()), nil +} + +// UnmarshalText implements the encoding.TextUnmarshaler interface. +// The date is expected to be a string in a format accepted by ParseDate. +func (d *Date) UnmarshalText(data []byte) error { + var err error + *d, err = ParseDate(string(data)) + return err +} + +// A Time represents a time with nanosecond precision. +// +// This type does not include location information, and therefore does not +// describe a unique moment in time. +// +// This type exists to represent the TIME type in storage-based APIs like BigQuery. +// Most operations on Times are unlikely to be meaningful. Prefer the DateTime type. +type Time struct { + Hour int // The hour of the day in 24-hour format; range [0-23] + Minute int // The minute of the hour; range [0-59] + Second int // The second of the minute; range [0-59] + Nanosecond int // The nanosecond of the second; range [0-999999999] +} + +// TimeOf returns the Time representing the time of day in which a time occurs +// in that time's location. It ignores the date. +func TimeOf(t time.Time) Time { + var tm Time + tm.Hour, tm.Minute, tm.Second = t.Clock() + tm.Nanosecond = t.Nanosecond() + return tm +} + +// ParseTime parses a string and returns the time value it represents. +// ParseTime accepts an extended form of the RFC3339 partial-time format. After +// the HH:MM:SS part of the string, an optional fractional part may appear, +// consisting of a decimal point followed by one to nine decimal digits. +// (RFC3339 admits only one digit after the decimal point). +func ParseTime(s string) (Time, error) { + t, err := time.Parse("15:04:05.999999999", s) + if err != nil { + return Time{}, err + } + return TimeOf(t), nil +} + +// String returns the date in the format described in ParseTime. If Nanoseconds +// is zero, no fractional part will be generated. Otherwise, the result will +// end with a fractional part consisting of a decimal point and nine digits. +func (t Time) String() string { + s := fmt.Sprintf("%02d:%02d:%02d", t.Hour, t.Minute, t.Second) + if t.Nanosecond == 0 { + return s + } + return s + fmt.Sprintf(".%09d", t.Nanosecond) +} + +// IsValid reports whether the time is valid. +func (t Time) IsValid() bool { + // Construct a non-zero time. + tm := time.Date(2, 2, 2, t.Hour, t.Minute, t.Second, t.Nanosecond, time.UTC) + return TimeOf(tm) == t +} + +// MarshalText implements the encoding.TextMarshaler interface. +// The output is the result of t.String(). +func (t Time) MarshalText() ([]byte, error) { + return []byte(t.String()), nil +} + +// UnmarshalText implements the encoding.TextUnmarshaler interface. +// The time is expected to be a string in a format accepted by ParseTime. +func (t *Time) UnmarshalText(data []byte) error { + var err error + *t, err = ParseTime(string(data)) + return err +} + +// A DateTime represents a date and time. +// +// This type does not include location information, and therefore does not +// describe a unique moment in time. +type DateTime struct { + Date Date + Time Time +} + +// Note: We deliberately do not embed Date into DateTime, to avoid promoting AddDays and Sub. + +// DateTimeOf returns the DateTime in which a time occurs in that time's location. +func DateTimeOf(t time.Time) DateTime { + return DateTime{ + Date: DateOf(t), + Time: TimeOf(t), + } +} + +// ParseDateTime parses a string and returns the DateTime it represents. +// ParseDateTime accepts a variant of the RFC3339 date-time format that omits +// the time offset but includes an optional fractional time, as described in +// ParseTime. Informally, the accepted format is +// YYYY-MM-DDTHH:MM:SS[.FFFFFFFFF] +// where the 'T' may be a lower-case 't'. +func ParseDateTime(s string) (DateTime, error) { + t, err := time.Parse("2006-01-02T15:04:05.999999999", s) + if err != nil { + t, err = time.Parse("2006-01-02t15:04:05.999999999", s) + if err != nil { + return DateTime{}, err + } + } + return DateTimeOf(t), nil +} + +// String returns the date in the format described in ParseDate. +func (dt DateTime) String() string { + return dt.Date.String() + "T" + dt.Time.String() +} + +// IsValid reports whether the datetime is valid. +func (dt DateTime) IsValid() bool { + return dt.Date.IsValid() && dt.Time.IsValid() +} + +// In returns the time corresponding to the DateTime in the given location. +// +// If the time is missing or ambigous at the location, In returns the same +// result as time.Date. For example, if loc is America/Indiana/Vincennes, then +// both +// time.Date(1955, time.May, 1, 0, 30, 0, 0, loc) +// and +// civil.DateTime{ +// civil.Date{Year: 1955, Month: time.May, Day: 1}}, +// civil.Time{Minute: 30}}.In(loc) +// return 23:30:00 on April 30, 1955. +// +// In panics if loc is nil. +func (dt DateTime) In(loc *time.Location) time.Time { + return time.Date(dt.Date.Year, dt.Date.Month, dt.Date.Day, dt.Time.Hour, dt.Time.Minute, dt.Time.Second, dt.Time.Nanosecond, loc) +} + +// Before reports whether dt1 occurs before dt2. +func (dt1 DateTime) Before(dt2 DateTime) bool { + return dt1.In(time.UTC).Before(dt2.In(time.UTC)) +} + +// After reports whether dt1 occurs after dt2. +func (dt1 DateTime) After(dt2 DateTime) bool { + return dt2.Before(dt1) +} + +// MarshalText implements the encoding.TextMarshaler interface. +// The output is the result of dt.String(). +func (dt DateTime) MarshalText() ([]byte, error) { + return []byte(dt.String()), nil +} + +// UnmarshalText implements the encoding.TextUnmarshaler interface. +// The datetime is expected to be a string in a format accepted by ParseDateTime +func (dt *DateTime) UnmarshalText(data []byte) error { + var err error + *dt, err = ParseDateTime(string(data)) + return err +} diff --git a/vendor/document/logs/logs.go b/vendor/document/logs/logs.go new file mode 100644 index 0000000..ee29b8f --- /dev/null +++ b/vendor/document/logs/logs.go @@ -0,0 +1,148 @@ +package logs + +import ( + "fmt" + "os" + "runtime" + "time" +) + +const ( + LOG_ERROR = iota + LOG_WARING + LOG_INFO + LOG_DEBUG +) + +var log *mylog + +/* + * 初始化 + */ +func init() { + log = newMylog() +} + +func Init(dir string, file string, level int, savefile bool) { + log.setDir(dir) + log.setFile(file) + log.setLevel(level) + log.setSavefile(savefile) +} + +func Error(err ...interface{}) { + log.write(LOG_ERROR, fmt.Sprint(err...)) +} + +func Waring(war ...interface{}) { + log.write(LOG_WARING, fmt.Sprint(war...)) +} +func SetLevel(level int) { + log.setLevel(level) +} +func Info(info ...interface{}) { + log.write(LOG_INFO, fmt.Sprint(info...)) +} + +func Debug(deb ...interface{}) { + log.write(LOG_DEBUG, fmt.Sprint(deb...)) +} + +/* + * 日志执行函数 + */ +type mylog struct { + log chan string // 日志chan + dir string // 日志存放目录 + file string // 日志文件名 + savefile bool // 是否保存到文件 + level int // 日志级别 +} + +func newMylog() *mylog { + log := &mylog{} + + log.log = make(chan string, 100) + log.dir = "/opt/logs" + log.file = "out" + log.savefile = false + + go log.run() + return log +} + +func (l *mylog) setDir(dir string) { + l.dir = dir +} + +func (l *mylog) setFile(file string) { + l.file = file +} + +func (l *mylog) setSavefile(b bool) { + l.savefile = b +} + +func (l *mylog) setLevel(level int) { + l.level = level +} + +func (l *mylog) getLevelString(level int) string { + switch level { + case LOG_ERROR: + return "ERROR" + case LOG_WARING: + return "WARING" + case LOG_INFO: + return "INFO" + case LOG_DEBUG: + return "DEBUG" + } + + return "unknown" +} + +func (l *mylog) write(level int, str string) { + // 判断级别 + if level > l.level { + return + } + + // 输出日志 + pc, _, line, _ := runtime.Caller(2) + p := runtime.FuncForPC(pc) + t := time.Now() + str = fmt.Sprintf("[%04d-%02d-%02d %02d:%02d:%02d] [%s] %s(%d): %s\n", + t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), + l.getLevelString(level), p.Name(), line, str) + // 输出到控制台 + if false == l.savefile { + fmt.Print(str) + return + } + + // 输出到文件 + l.log <- str +} + +func (l *mylog) run() { + for { + str := <-l.log + + // 判断文件夹是否存在 + _, err := os.Stat(l.dir) + if nil != err { + os.MkdirAll(l.dir, os.ModePerm) + } + + // 获取时间 + t := time.Now() + path := fmt.Sprintf("%s/%s-%04d-%02d-%02d.log", l.dir, l.file, + t.Year(), t.Month(), t.Day()) + fp, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModePerm) + if nil == err { + fp.WriteString(str) + fp.Close() + } + } +} diff --git a/vendor/git.jiaxianghudong.com/go/utils/README.md b/vendor/git.jiaxianghudong.com/go/utils/README.md new file mode 100644 index 0000000..e69de29 diff --git a/vendor/git.jiaxianghudong.com/go/utils/bytebuffer.go b/vendor/git.jiaxianghudong.com/go/utils/bytebuffer.go new file mode 100644 index 0000000..73b1216 --- /dev/null +++ b/vendor/git.jiaxianghudong.com/go/utils/bytebuffer.go @@ -0,0 +1,87 @@ +package utils + +// 加入8字节 +func Put8bit(buf []byte, n byte) []byte { + return append(buf, n) +} + +// 加入16字节 +func Put16bit(buf []byte, n uint16) []byte { + var by [2]byte + + by[0] = byte((n >> 8) & 0xff) + by[1] = byte(n & 0xff) + + return append(buf, by[:]...) +} + +// 加入32字节 +func Put32bit(buf []byte, n uint32) []byte { + var by [4]byte + + by[0] = byte((n >> 24) & 0xff) + by[1] = byte((n >> 16) & 0xff) + by[2] = byte((n >> 8) & 0xff) + by[3] = byte(n & 0xff) + + return append(buf, by[:]...) +} + +// 加入64字节 +func Put64bit(buf []byte, n uint64) []byte { + var by [8]byte + + by[0] = byte((n >> 56) & 0xff) + by[1] = byte((n >> 48) & 0xff) + by[2] = byte((n >> 40) & 0xff) + by[3] = byte((n >> 32) & 0xff) + by[4] = byte((n >> 24) & 0xff) + by[5] = byte((n >> 16) & 0xff) + by[6] = byte((n >> 8) & 0xff) + by[7] = byte(n & 0xff) + + return append(buf, by[:]...) +} + +// 获取8bit +func Get8bit(buf []byte, start int) byte { + return buf[start] +} + +// 获取16bit +func Get16bit(buf []byte, start int) uint16 { + var ret uint16 + + ret = uint16(buf[start]) << 8 + ret |= uint16(buf[start+1]) + + return ret +} + +// 获取32big +func Get32bit(buf []byte, start int) uint32 { + var ret uint32 + + ret = uint32(buf[start]) << 24 + ret |= uint32(buf[start+1]) << 16 + ret |= uint32(buf[start+2]) << 8 + ret |= uint32(buf[start+3]) + + return ret +} + +// 获取64bit +func Get64bit(buf []byte, start int) uint64 { + var ret uint64 + + ret = uint64(buf[start]) << 56 + ret |= uint64(buf[start+1]) << 48 + ret |= uint64(buf[start+2]) << 40 + ret |= uint64(buf[start+3]) << 32 + ret |= uint64(buf[start+4]) << 24 + ret |= uint64(buf[start+5]) << 16 + ret |= uint64(buf[start+6]) << 8 + ret |= uint64(buf[start+7]) + + return ret +} diff --git a/vendor/git.jiaxianghudong.com/go/utils/coding.go b/vendor/git.jiaxianghudong.com/go/utils/coding.go new file mode 100644 index 0000000..18180b2 --- /dev/null +++ b/vendor/git.jiaxianghudong.com/go/utils/coding.go @@ -0,0 +1,289 @@ +package utils + +import ( + "encoding/json" + "strings" + "log" + "time" + "fmt" + "encoding/pem" + "crypto/x509" + "crypto/rsa" + "encoding/base64" + "errors" + "io" + "net/url" + "hash/crc32" + crand "crypto/rand" + "crypto/hmac" + "crypto/sha1" + "crypto/md5" +) + +// md5 +func Md5Sum(text string) string { + h := md5.New() + io.WriteString(h, text) + return fmt.Sprintf("%x", h.Sum(nil)) +} + +// 加解密函数 根据dz的Authcode改写的go版本 +// params[0] 加密or解密 bool true:加密 false:解密 默认false +// params[1] 秘钥 +// params[2] 加密:过期时间 +// params[3] 动态秘钥长度 默认:4位 不能大于32位 +func Authcode(text string, params ...interface{}) string { + defer func() { + if err := recover(); err != nil { + log.Printf("authcode error:%#v", err) + } + }() + + l := len(params) + + isEncode := false + key := "DH-Framework" + expiry := 0 + cKeyLen := 10 + + if l > 0 { + isEncode = params[0].(bool) + } + + if l > 1 { + key = params[1].(string) + } + + if l > 2 { + expiry = params[2].(int) + if expiry < 0 { + expiry = 0 + } + } + + if l > 3 { + cKeyLen = params[3].(int) + if cKeyLen < 0 { + cKeyLen = 0 + } + } + if cKeyLen > 32 { + cKeyLen = 32 + } + + timestamp := time.Now().Unix() + + // md5加密key + mKey := Md5Sum(key) + + // 参与加密的 + keyA := Md5Sum(mKey[0:16]) + // 用于验证数据有效性的 + keyB := Md5Sum(mKey[16:]) + // 动态部分 + var keyC string + if cKeyLen > 0 { + if isEncode { + // 加密的时候,动态获取一个秘钥 + keyC = Md5Sum(fmt.Sprint(timestamp))[32 - cKeyLen:] + } else { + // 解密的时候从头部获取动态秘钥部分 + keyC = text[0:cKeyLen] + } + } + + // 加入了动态的秘钥 + cryptKey := keyA + Md5Sum(keyA + keyC) + // 秘钥长度 + keyLen := len(cryptKey) + if isEncode { + // 加密 前10位是过期验证字符串 10-26位字符串验证 + var d int64 + if expiry > 0 { + d = timestamp + int64(expiry) + } + text = fmt.Sprintf("%010d%s%s", d, Md5Sum(text + keyB)[0:16], text) + } else { + // 解密 + text = string(Base64Decode(text[cKeyLen:])) + } + + // 字符串长度 + textLen := len(text) + if textLen <= 0 { + panic(fmt.Sprintf("auth[%s]textLen<=0", text)) + } + + // 密匙簿 + box := Range(0, 256) + // 对称算法 + var rndKey []int + cryptKeyB := []byte(cryptKey) + for i := 0; i < 256; i++ { + pos := i % keyLen + rndKey = append(rndKey, int(cryptKeyB[pos])) + } + + j := 0 + for i := 0; i < 256; i++ { + j = (j + box[i] + rndKey[i]) % 256 + box[i], box[j] = box[j], box[i] + } + + textB := []byte(text) + a := 0 + j = 0 + var result []byte + for i := 0; i < textLen; i++ { + a = (a + 1) % 256 + j = (j + box[a]) % 256 + box[a], box[j] = box[j], box[a] + result = append(result, byte(int(textB[i]) ^ (box[(box[a] + box[j]) % 256]))) + } + + if isEncode { + return keyC + strings.Replace(Base64Encode(result), "=", "", -1) + } + + // 获取前10位,判断过期时间 + d := Atoi64(string(result[0:10]), 0) + if (d == 0 || d - timestamp > 0) && string(result[10:26]) == Md5Sum(string(result[26:]) + keyB)[0:16] { + return string(result[26:]) + } + + panic(fmt.Sprintf("auth[%s]", text)) + + return "" +} + +// AuthcodeUrl 处理Authcode函数的加密解密结果以便url传输 +func AuthcodeUrl(text string, params ...interface{}) string { + isEncode := false + if len(params) > 0 { + isEncode = params[0].(bool) + } + if isEncode { //加密 + return strings.Replace(strings.Replace(Authcode(text, params...), "+", ",", -1), "/", "-", -1) + } else { + return Authcode(strings.Replace(strings.Replace(text, ",", "+", -1), "-", "/", -1), params...) + } +} + +// JsonEncode 编码JSON +func JsonEncode(m interface{}) string { + b, err := json.Marshal(m) + if err != nil { + log.Printf("Json Encode[%#v] Error:%s", m, err.Error()) + return "" + } + return string(b) +} + +// JsonDecode 解码JSON +func JsonDecode(str string, v ...interface{}) (interface{}, error) { + var m interface{} + if len(v) > 0 { + m = v[0] + } else { + m = make(map[string]interface{}) + } + + err := json.Unmarshal([]byte(str), &m) + if err != nil { + return nil, err + } + + return m, nil +} + +func Crc32(text string) string { + h := crc32.NewIEEE() + io.WriteString(h, text) + return fmt.Sprintf("%d", h.Sum32()) +} + +// RsaEncode rsa加密 +func RsaEncode(b, rsaKey []byte) ([]byte, error) { + block, _ := pem.Decode(rsaKey) + if block == nil { + return b, errors.New("key error") + } + pub, err := x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + return b, err + } + return rsa.EncryptPKCS1v15(crand.Reader, pub.(*rsa.PublicKey), b) +} + +// RsaDecode rsa解密 +func RsaDecode(b, rsaKey []byte) ([]byte, error) { + block, _ := pem.Decode(rsaKey) + if block == nil { + return b, errors.New("key error") + } + priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) + if err != nil { + return b, err + } + return rsa.DecryptPKCS1v15(crand.Reader, priv, b) +} + +func HashHmac(data, key string) string { + mac := hmac.New(sha1.New, []byte(key)) + mac.Write([]byte(data)) + return fmt.Sprintf("%x", mac.Sum(nil)) +} + +func HashHmacRaw(data, key string) string { + mac := hmac.New(sha1.New, []byte(key)) + mac.Write([]byte(data)) + return fmt.Sprintf("%s", mac.Sum(nil)) +} + +// Base64Encode Base64编码 +func Base64Encode(b []byte) string { + return base64.StdEncoding.EncodeToString(b) +} + +// Base64Decode Base64解码 +func Base64Decode(str string) []byte { + var b []byte + var err error + x := len(str) * 3 % 4 + switch { + case x == 2: + str += "==" + case x == 1: + str += "=" + } + if b, err = base64.StdEncoding.DecodeString(str); err != nil { + return b + } + + return b +} + +// UrlEncode 编码 +func UrlEncode(str string) string { + return url.QueryEscape(str) +} + +// UrlDecode 解码 +func UrlDecode(str string) string { + ret, _ := url.QueryUnescape(str) + return ret +} + +/*func Urlencode(str string) string { + return base64.URLEncoding.EncodeToString([]byte(str)) +} + +func Urldecode(str string) string { + b, e := base64.URLEncoding.DecodeString(str) + if e != nil { + log.Printf("urldecode error:%s", e.Error()) + return "" + } + + return string(b) +}*/ diff --git a/vendor/git.jiaxianghudong.com/go/utils/conf.go b/vendor/git.jiaxianghudong.com/go/utils/conf.go new file mode 100644 index 0000000..af8814f --- /dev/null +++ b/vendor/git.jiaxianghudong.com/go/utils/conf.go @@ -0,0 +1,80 @@ +package utils + +import ( + "errors" + "io/ioutil" + "os" + "os/exec" + "path/filepath" +) + +const ( + FILE_OPEN_TYPE_READ int = 0 + FILE_OPEN_TYPE_WRITE int = 1 + FILE_OPEN_TYPE_APPEND int = 2 +) + +// ReadTextFile 读取文件 +func ReadTextFile(path string) string { + fp, err := os.Open(path) + if nil != err { + return "" + } + defer fp.Close() + d, err := ioutil.ReadAll(fp) + if nil != err { + return "" + } + return string(d) +} + +/* + * 读取配置文件 + */ +func ReadConfFile(file string) string { + return ReadTextFile(GetConfPath(file)) +} + +// 获取配置文件路径 +func GetConfPath(fname string) string { + // 绝对路径 + if len(fname) > 2 && ('/' == fname[0] || ':' == fname[1]) { + return fname + } + return GetFilePathBaseExe("./" + fname) +} + +// 以exe为根节点获取文件路径 +func GetFilePathBaseExe(fname string) string { + // 绝对路径 + if len(fname) > 2 && ('/' == fname[0] || ':' == fname[1]) { + return fname + } + // 相对路径 + file, _ := exec.LookPath(os.Args[0]) + return filepath.Join(filepath.Dir(file), fname) +} + +// 创建目录 +func CreateDir(dirName string) error { + // 判断目录是否存在 + if _, err := os.Stat(dirName); false == os.IsNotExist(err) { + return nil + } + + // 分解上层目录 + pdir := filepath.Dir(dirName) + if "" == pdir { + return errors.New("error dir format") + } + + // 判断目录是否存在 + if _, err := os.Stat(pdir); os.IsNotExist(err) { + err = CreateDir(pdir) + if nil != err { + return err + } + } + + return os.Mkdir(dirName, 0755) +} diff --git a/vendor/git.jiaxianghudong.com/go/utils/convert.go b/vendor/git.jiaxianghudong.com/go/utils/convert.go new file mode 100644 index 0000000..c159409 --- /dev/null +++ b/vendor/git.jiaxianghudong.com/go/utils/convert.go @@ -0,0 +1,329 @@ +package utils + +import ( + "bytes" + "fmt" + "io/ioutil" + "reflect" + "regexp" + "strconv" + "strings" + "time" + + "golang.org/x/text/encoding/simplifiedchinese" + "golang.org/x/text/transform" +) + +// GetTypeName 获取参数类型 +func GetTypeName(v interface{}) string { + return reflect.TypeOf(v).String() +} + +// Btoi 布尔值转整形 +func Btoi(b bool) int { + if b { + return 1 + } + return 0 +} + +// Itoa 整型转字符串 +func Itoa(i int) string { + return strconv.Itoa(i) +} + +// Atoi 转换成整型 +func Atoi(s string, d ...int) int { + i, err := strconv.Atoi(s) + if err != nil { + if len(d) > 0 { + return d[0] + } else { + return 0 + } + } + + return i +} + +// AtoUi 转换成无符号整型 +func AtoUi(s string) uint { + return uint(Atoi64(s)) +} + +// Atoi64 转换成整型int64 +func Atoi64(s string, d ...int64) int64 { + i, err := strconv.ParseInt(s, 10, 64) + if err != nil { + if len(d) > 0 { + return d[0] + } else { + return 0 + } + } + + return i +} + +// AtoUi64 转换成整型float64 +func AtoUi64(s string, d ...uint64) uint64 { + i, err := strconv.ParseUint(s, 10, 64) + if err != nil { + if len(d) > 0 { + return d[0] + } else { + return 0 + } + } + + return i +} + +// Atof 转换成float32整型 +func Atof(s string, d ...float32) float32 { + f, err := strconv.ParseFloat(s, 32) + if err != nil { + if len(d) > 0 { + return d[0] + } else { + return 0 + } + } + + return float32(f) +} + +// Atof64 转换成整型float64 +func Atof64(s string, d ...float64) float64 { + f, err := strconv.ParseFloat(s, 64) + if err != nil { + if len(d) > 0 { + return d[0] + } else { + return 0 + } + } + + return f +} + +// UitoA 32位无符号整形转字符串 +func UitoA(i uint) string { + return strconv.FormatUint(uint64(i), 10) +} + +// Ui32toA 32位无符号整形转字符串 +func Ui32toA(i uint32) string { + return strconv.FormatUint(uint64(i), 10) +} + +// Ui64toA 64位无符号整形转字符串 +func Ui64toA(i uint64) string { + return strconv.FormatUint(i, 10) +} + +// I64toA 64位整形转字符串 +func I64toA(i int64) string { + return strconv.FormatInt(i, 10) +} + +// F32toA 32位浮点数转字符串 +func F32toA(f float32) string { + return F64toA(float64(f)) +} + +// F64toA 64位浮点数转字符串 +func F64toA(f float64) string { + return strconv.FormatFloat(f, 'f', -1, 64) +} + +// DateFormat 日期格式化 +func DateFormat(format string, t time.Time) string { + patterns := []string{ + // 年 + "Y", "2006", // 4 位数字完整表示的年份 + "y", "06", // 2 位数字表示的年份 + + // 月 + "m", "01", // 数字表示的月份,有前导零 + "n", "1", // 数字表示的月份,没有前导零 + "M", "Jan", // 三个字母缩写表示的月份 + "F", "January", // 月份,完整的文本格式,例如 January 或者 March + + // 日 + "d", "02", // 月份中的第几天,有前导零的 2 位数字 + "j", "2", // 月份中的第几天,没有前导零 + + "D", "Mon", // 星期几,文本表示,3 个字母 + "l", "Monday", // 星期几,完整的文本格式;L的小写字母 + + // 时间 + "g", "3", // 小时,12 小时格式,没有前导零 + "G", "15", // 小时,24 小时格式,没有前导零 + "h", "03", // 小时,12 小时格式,有前导零 + "H", "15", // 小时,24 小时格式,有前导零 + + "a", "pm", // 小写的上午和下午值 + "A", "PM", // 小写的上午和下午值 + + "i", "04", // 有前导零的分钟数 + "s", "05", // 秒数,有前导零 + } + replacer := strings.NewReplacer(patterns...) + format = replacer.Replace(format) + return t.Format(format) +} + +// StrToLocalTime 字符串转本地时间 +func StrToLocalTime(value string) (time.Time, error) { + if value == "" { + return time.Time{}, nil + } + zoneName, offset := time.Now().Zone() + + zoneValue := offset / 3600 * 100 + if zoneValue > 0 { + value += fmt.Sprintf(" +%04d", zoneValue) + } else { + value += fmt.Sprintf(" -%04d", zoneValue) + } + + if zoneName != "" { + value += " " + zoneName + } + return StrToTime(value) +} + +// StrToTime 字符串转时间 +func StrToTime(value string) (time.Time, error) { + if value == "" { + return time.Time{}, nil + } + layouts := []string{ + "2006-01-02 15:04:05 -0700 MST", + "2006-01-02 15:04:05 -0700", + "2006-01-02 15:04:05", + "2006/01/02 15:04:05 -0700 MST", + "2006/01/02 15:04:05 -0700", + "2006/01/02 15:04:05", + "2006-01-02 -0700 MST", + "2006-01-02 -0700", + "2006-01-02", + "2006/01/02 -0700 MST", + "2006/01/02 -0700", + "2006/01/02", + "2006-01-02 15:04:05 -0700 -0700", + "2006/01/02 15:04:05 -0700 -0700", + "2006-01-02 -0700 -0700", + "2006/01/02 -0700 -0700", + time.ANSIC, + time.UnixDate, + time.RubyDate, + time.RFC822, + time.RFC822Z, + time.RFC850, + time.RFC1123, + time.RFC1123Z, + time.RFC3339, + time.RFC3339Nano, + time.Kitchen, + time.Stamp, + time.StampMilli, + time.StampMicro, + time.StampNano, + } + + var t time.Time + var err error + for _, layout := range layouts { + t, err = time.ParseInLocation(layout, value, time.Local) + if err == nil { + return t, nil + } + } + return time.Time{}, err +} + +// StructToMap 结构转map +func StructToMap(data interface{}) map[string]interface{} { + result := make(map[string]interface{}) + elem := reflect.ValueOf(data).Elem() + size := elem.NumField() + + for i := 0; i < size; i++ { + field := elem.Type().Field(i).Name + value := elem.Field(i).Interface() + result[field] = value + } + + return result +} + +// 带xml标签的Struct结构转map,用xml标注做key +func XMLStructToMap(data interface{}) map[string]interface{} { + result := make(map[string]interface{}) + elem := reflect.ValueOf(data).Elem() + size := elem.NumField() + + for i := 0; i < size; i++ { + field := elem.Type().Field(i).Tag.Get("xml") + value := elem.Field(i).Interface() + result[field] = value + } + + return result +} + +// Ip2long IP转长整型 +func Ip2long(ipstr string) (ip uint32) { + r := `^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})` + reg, err := regexp.Compile(r) + if err != nil { + return + } + ips := reg.FindStringSubmatch(ipstr) + if ips == nil { + return + } + + ip1, _ := strconv.Atoi(ips[1]) + ip2, _ := strconv.Atoi(ips[2]) + ip3, _ := strconv.Atoi(ips[3]) + ip4, _ := strconv.Atoi(ips[4]) + + if ip1 > 255 || ip2 > 255 || ip3 > 255 || ip4 > 255 { + return + } + + ip += uint32(ip1 * 0x1000000) + ip += uint32(ip2 * 0x10000) + ip += uint32(ip3 * 0x100) + ip += uint32(ip4) + + return +} + +// Long2ip 长整型转IP +func Long2ip(ip uint32) string { + return fmt.Sprintf("%d.%d.%d.%d", ip>>24, ip<<8>>24, ip<<16>>24, ip<<24>>24) +} + +// GbkToUtf8 GBK转UTF-8 +func GbkToUtf8(s []byte) ([]byte, error) { + reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewDecoder()) + d, e := ioutil.ReadAll(reader) + if e != nil { + return nil, e + } + return d, nil +} + +// Utf8ToGbk UTF-8转GBK +func Utf8ToGbk(s []byte) ([]byte, error) { + reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewEncoder()) + d, e := ioutil.ReadAll(reader) + if e != nil { + return nil, e + } + return d, nil +} diff --git a/vendor/git.jiaxianghudong.com/go/utils/counter.go b/vendor/git.jiaxianghudong.com/go/utils/counter.go new file mode 100644 index 0000000..0965e6e --- /dev/null +++ b/vendor/git.jiaxianghudong.com/go/utils/counter.go @@ -0,0 +1,25 @@ +package utils + +import ( + "sync/atomic" +) + +// Counter 原子计数器 +type Counter struct { + v int64 +} + +// Add 计数加 +func (c *Counter) Add(i int64) { + atomic.AddInt64(&c.v, i) +} + +// Get 取计数 +func (c *Counter) Get() int64 { + return c.v +} + +// Reset 重置计数器 +func (c *Counter) Reset() { + c.Add(c.v * -1) +} \ No newline at end of file diff --git a/vendor/git.jiaxianghudong.com/go/utils/file.go b/vendor/git.jiaxianghudong.com/go/utils/file.go new file mode 100644 index 0000000..c017aa0 --- /dev/null +++ b/vendor/git.jiaxianghudong.com/go/utils/file.go @@ -0,0 +1,75 @@ +package utils + +import ( + "bytes" + "errors" + "io/ioutil" + "os" + "runtime" +) + +// FileIsExist 检查文件是否存在 +func FileIsExist(path string) bool { + _, err := os.Stat(path) + if err != nil && os.IsNotExist(err) { + return false + } + return true +} + +// GetFileContents 读取文件内容 +func GetFileContents(path string) string { + fi, err := os.Open(path) + if err != nil { + return "" + } + defer fi.Close() + fd, err := ioutil.ReadAll(fi) + return string(bytes.Trim(fd, "\xef\xbb\xbf")) +} + +// DirIsExist 检查目录是否存在 +func DirIsExist(path string) bool { + fileinfo, err := os.Stat(path) + if err != nil { + return os.IsExist(err) + } else { + return fileinfo.IsDir() + } +} + +// 打开文件 +func OpenFile(path string, fileName string, openType int) (*os.File, error) { + + fileFullPath := path + "/" + fileName + if runtime.GOOS == "windows" { + fileFullPath = path + "\\" + fileName + } + isFileExist := FileIsExist(fileFullPath) + + switch openType { + case FILE_OPEN_TYPE_READ: + if isFileExist { + f, err := os.OpenFile(fileFullPath, os.O_RDONLY, 0644) + return f, err + } else { + return nil, errors.New("file not exist") + } + case FILE_OPEN_TYPE_WRITE: + if isFileExist { + return nil, errors.New("file already existed") + } else { + f, err := os.OpenFile(fileFullPath, os.O_CREATE|os.O_WRONLY, 0644) + return f, err + } + case FILE_OPEN_TYPE_APPEND: + if !isFileExist { + f, err := os.OpenFile(fileFullPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) + return f, err + } else { + f, err := os.OpenFile(fileFullPath, os.O_APPEND|os.O_WRONLY, 0644) + return f, err + } + } + return nil, nil +} diff --git a/vendor/git.jiaxianghudong.com/go/utils/http_helper.go b/vendor/git.jiaxianghudong.com/go/utils/http_helper.go new file mode 100644 index 0000000..04ed988 --- /dev/null +++ b/vendor/git.jiaxianghudong.com/go/utils/http_helper.go @@ -0,0 +1,144 @@ +package utils + +import ( + "bytes" + "strings" + + "crypto/tls" + "errors" + "fmt" + "io/ioutil" + "net/http" + "net/url" +) + +// Get +func Get(apiUrl string, parm map[string]string, header map[string]string, isHttps bool) ([]byte, error) { + + if len(parm) > 0 { + apiUrl = fmt.Sprintf("%s%s", apiUrl, "?") + p := "" + for k, v := range parm { + if p == "" { + p = fmt.Sprintf("%s=%s", k, v) + } else { + p = fmt.Sprintf("%s&%s=%s", p, k, v) + } + } + apiUrl = fmt.Sprintf("%s%s", apiUrl, p) + } + + client := &http.Client{} + + if isHttps { + client.Transport = &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + } + } + reqest, _ := http.NewRequest("GET", apiUrl, nil) + + for k, v := range header { + reqest.Header.Set(k, v) + } + + response, err := client.Do(reqest) + if nil != err { + return nil, err + } + + defer response.Body.Close() + if response.StatusCode != 200 { + return nil, errors.New(response.Status) + } + + body, err := ioutil.ReadAll(response.Body) + if nil != err { + return nil, err + } + + return body, nil +} + +// post +func Post(apiUrl string, data []byte, header map[string]string, isHttps bool) ([]byte, error) { + + client := &http.Client{} + + if isHttps { + client.Transport = &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + } + } + reqest, _ := http.NewRequest("POST", apiUrl, bytes.NewReader(data)) + + for k, v := range header { + reqest.Header.Set(k, v) + } + + response, err := client.Do(reqest) + if nil != err { + return nil, err + } + + defer response.Body.Close() + if response.StatusCode != 200 { + return nil, errors.New(response.Status) + } + + body, err := ioutil.ReadAll(response.Body) + if nil != err { + return nil, err + } + + return body, nil +} + +// post +func PostMap(apiUrl string, parm map[string]string, header map[string]string, isHttps bool) ([]byte, error) { + + data := url.Values{} + for k, v := range parm { + data.Set(k, v) + } + + reqParams := ioutil.NopCloser(strings.NewReader(data.Encode())) + client := &http.Client{} + + if isHttps { + client.Transport = &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + } + } + reqest, _ := http.NewRequest("POST", apiUrl, reqParams) + + for k, v := range header { + reqest.Header.Set(k, v) + } + + response, err := client.Do(reqest) + if nil != err { + return nil, err + } + + defer response.Body.Close() + if response.StatusCode != 200 { + return nil, errors.New(response.Status) + } + + body, err := ioutil.ReadAll(response.Body) + if nil != err { + return nil, err + } + + return body, nil +} + +// 获取远程ip +func GetRemoteIP(r *http.Request) string { + addr := r.Header.Get("Remote_addr") + if addr == "" { + addr = r.RemoteAddr + } + + return strings.Split(addr, ":")[0] +} diff --git a/vendor/git.jiaxianghudong.com/go/utils/human.go b/vendor/git.jiaxianghudong.com/go/utils/human.go new file mode 100644 index 0000000..500ae42 --- /dev/null +++ b/vendor/git.jiaxianghudong.com/go/utils/human.go @@ -0,0 +1,36 @@ +package utils + +import ( + "fmt" +) + +// HumanTimeSecond 格式化秒数 +func HumanTimeSecond(s int64, separator ...string) string { + const ( + Minute = 60 + Hour = 60 * Minute + Day = 24 * Hour + ) + var d, h, m int64 + + d = s / Day + s = s % Day + h = s / Hour + s = s % Hour + m = s / Minute + s = s % Minute + + var sep string + if len(separator) == 1 { + sep = separator[0] + } + + if d > 0 { + return fmt.Sprintf("%dd%s%dh%s%dm%s%ds", d, sep, h, sep, m, sep, s) + } else if h > 0 { + return fmt.Sprintf("%dh%s%dm%s%ds", h, sep, m, sep, s) + } else if m > 0 { + return fmt.Sprintf("%dm%s%ds", m, sep, s) + } + return fmt.Sprintf("%ds", s) +} diff --git a/vendor/git.jiaxianghudong.com/go/utils/image.go b/vendor/git.jiaxianghudong.com/go/utils/image.go new file mode 100644 index 0000000..353f015 --- /dev/null +++ b/vendor/git.jiaxianghudong.com/go/utils/image.go @@ -0,0 +1,118 @@ +package utils + +import ( + "net/http" + "os" + "strconv" + "time" + "path" + "io" + "strings" + "errors" + "github.com/dustin/go-humanize" + "github.com/disintegration/imaging" +) + +type Size interface { + Size() int64 //字节 +} + +// 图片上传器 +type ImageUploader struct { + UploadPath string //图片保存的磁盘目录 + UrlPath string //上传图片的URL路径 + FileName string //文件名(不含扩展名) + AllowExtName string //允许的扩展名 + Rename bool //是否重命名文件 + Cut bool //是否裁剪图片 + Resize bool //是否重新调整大小 + ToWidth int //要操作的图片宽度 + ToHeight int //要操作的图片高度 + MaxSize uint64 //图片大小,字节 +} + +// 创建一个新的图片上传器 +func NewImageUploader(path string) *ImageUploader { + return &ImageUploader{ + UploadPath: path, + UrlPath: "/upload", + AllowExtName: "gif,jpg,png,jpeg", + Rename: true, + MaxSize: 2000000, //2M + } +} + +// 上传图片 +func (this *ImageUploader) Upload(r *http.Request) (string, error) { + r.ParseMultipartForm(32 << 20) + if r.MultipartForm != nil && r.MultipartForm.File != nil { + file, handler, err := r.FormFile("file") + if err != nil { + return "", err + } + defer file.Close() + + //检查图片大小 + if sizeInterface, ok := file.(Size); ok { + size := uint64(sizeInterface.Size()) + if size > this.MaxSize { + return "", errors.New("图片过大,请换一张小于 " + humanize.Bytes(size) + " 的图片重新上传") + } + } else { + return "", errors.New("图片尺寸超限或未能取得图片大小,请尝试换一张图片") + } + + if !DirIsExist(this.UploadPath) { + err := os.MkdirAll(this.UploadPath, os.ModePerm) + if err != nil { + return "", err + } + } + + extname := strings.ToLower(path.Ext(handler.Filename)) + allowExt := strings.Split(this.AllowExtName, ",") + if InArray(Substr(extname, 1), allowExt) == -1 { + return "", errors.New("不允许上传该格式的文件") + } + + filename := this.FileName + if filename == "" { + filename = path.Base(handler.Filename) + //唯一文件名 + if this.Rename { + filename = Md5Sum(strconv.FormatInt(time.Now().UnixNano(), 10)) + } + } + + if (this.Cut || this.Resize) && this.ToWidth > 0 && this.ToHeight > 0 { + srcImg, err := imaging.Decode(file) + if err != nil { + return "", err + } + + if this.Cut { + srcImg = imaging.CropAnchor(srcImg, this.ToWidth, this.ToHeight, imaging.Center) + } + + if this.Resize { + srcImg = imaging.Resize(srcImg, this.ToWidth, this.ToHeight, imaging.Lanczos) + } + err = imaging.Save(srcImg, this.UploadPath + filename + extname) + if err != nil { + return "", err + } + } else { + f, err := os.OpenFile(this.UploadPath + filename + extname, os.O_WRONLY|os.O_CREATE, 0666) + if err != nil { + return "", err + } + defer f.Close() + _, err = io.Copy(f, file) + if err != nil { + return "", err + } + } + return filename + extname, nil; + } + return "", errors.New("没有发现上传的图片") +} \ No newline at end of file diff --git a/vendor/git.jiaxianghudong.com/go/utils/lua.go b/vendor/git.jiaxianghudong.com/go/utils/lua.go new file mode 100644 index 0000000..dee2540 --- /dev/null +++ b/vendor/git.jiaxianghudong.com/go/utils/lua.go @@ -0,0 +1,107 @@ +package utils + +import ( + "strconv" + "strings" + "net/http" +) + +// buildLuaResponse构造Lua响应结果 +func BuildLuaResponse(m interface{}) string { + var ret string + if mm, ok := m.(map[interface{}]interface{}); ok { + for k, i := range mm { + vStr := "" + switch v := i.(type) { + case int: + vStr = strconv.Itoa(v) + case int8: + vStr = strconv.Itoa(int(v)) + case int16: + vStr = strconv.Itoa(int(v)) + case int32: + vStr = I64toA(int64(v)) + case int64: + vStr = I64toA(v) + case uint: + vStr = UitoA(v) + case uint8: + vStr = UitoA(uint(v)) + case uint16: + vStr = UitoA(uint(v)) + case uint32: + vStr = Ui32toA(v) + case uint64: + vStr = Ui64toA(v) + case bool: + if v { + vStr = "true" + } + case []interface{}: + tmp := make(map[interface{}]interface{}) + for kk, vv := range v { + tmp[kk] = vv + } + vStr = BuildLuaResponse(tmp) + case map[interface{}]interface{}: + vStr = BuildLuaResponse(v) + case map[string]string: + for ks, vs := range v { + vStr += `,` + ks + `=` + strings.Replace(vs, `"`, `\"`, -1) + } + vStr = "{" + Substr(vStr, 1) + "}" + case string: + vStr = `"` + strings.Replace(v, `"`, `\"`, -1) + `"` + default: + if vv, ok := v.(map[interface{}]interface{}); ok { + vStr = BuildLuaResponse(vv) + } + } + if vStr != "" { + switch v := k.(type) { + case int: + ret += `,[` + strconv.Itoa(v) + `]=` + vStr + case string: + ret += `,` + v + `=` + vStr + } + } + } + return "{" + Substr(ret, 1) + "}" + } + return "{}" +} + +// outputLuaMsg 输出lua格式提示信息 +func OutputLua(w http.ResponseWriter, m map[interface{}]interface{}) { + w.Write([]byte("return " + BuildLuaResponse(m))) +} + +// outputLuaMsg 输出lua格式提示信息 +func OutputLuaMsg(w http.ResponseWriter, msg string, code ...int) bool { + var c int = 120 + if len(code) >= 1 { + c = code[0] + } + OutputLua(w, NewLuaResult(msg, c)) + return c == 0 +} + +// outputLuaOk 输出lua格式成功信息 +func OutputLuaOk(w http.ResponseWriter, msg string) { + OutputLuaMsg(w, msg, 0) +} + +// 获取lua返回结果map +func NewLuaResult(params ...interface{}) map[interface{}]interface{} { + ret := make(map[interface{}]interface{}) + if len(params) > 0 { + ret["msg"] = params[0] + + if len(params) > 1 { + ret["status"] = params[1] + } else { + ret["status"] = 0 + } + } + return ret +} \ No newline at end of file diff --git a/vendor/git.jiaxianghudong.com/go/utils/progressbar.go b/vendor/git.jiaxianghudong.com/go/utils/progressbar.go new file mode 100644 index 0000000..7488b97 --- /dev/null +++ b/vendor/git.jiaxianghudong.com/go/utils/progressbar.go @@ -0,0 +1,91 @@ +package utils + +import ( + "fmt" + "time" +) + +// 进度条定义 +type ProgressBar struct { + Name string // 名称 + Total Counter // 总任务数 + Current *Counter // 当前已完成数量 + startTime time.Time // 任务开始时间 + exit chan struct{} // 是否退出进度条 + alreadyOutput bool +} + +// 完成指定数量的任务 +func (pgb *ProgressBar) Done(i ...int64) { + if len(i) == 1 { + pgb.Current.Add(i[0]) + } else { + pgb.Current.Add(1) + } +} + +// 退出进度条 +func (pgb *ProgressBar) Exit() { + pgb.exit <- struct{}{} + if pgb.alreadyOutput { + fmt.Println("") + } +} + +// 启动并显示进度条 +func (pgb *ProgressBar) Run() { + for { + select { + case <-pgb.exit: + return + case <-time.After(time.Second): + pgb.print() + } + } +} + +// 输出进度 +func (pgb *ProgressBar) print() { + var percent float64 = 0 + var per, surplus int64 + + cur := pgb.Current.Get() + if pgb.Total.Get() > 0 { + percent = float64(cur) / float64(pgb.Total.Get()) + } + useTime := int64(time.Now().Sub(pgb.startTime) / time.Second) + if useTime > 0 { + per = cur / useTime + } + if per > 0 { + surplus = (pgb.Total.Get() - cur) / per + } + + fmt.Printf("\r\x1b[36m%s[%.2f%%] %d/%d %d/ps used:%s surplus:%s\x1b[0m", pgb.Name, percent * 100, cur, pgb.Total.Get(), per, HumanTimeSecond(useTime), HumanTimeSecond(surplus)) + + if !pgb.alreadyOutput { + pgb.alreadyOutput = true + } +} + +// 创建一个进度条 +func NewPGBar(total int64, name ...string) *ProgressBar { + var n string + if len(name) == 1 && name[0] != "" { + n = name[0] + " " + } + return &ProgressBar{ + Name: n, + Total: Counter{v : total}, + Current: &Counter{}, + startTime: time.Now(), + exit: make(chan struct{}, 1), + } +} + +// 生成一个新的进度条并运行 +func NewAndRunPGBar(total int64, name ...string) *ProgressBar { + pgb := NewPGBar(total, name...) + go pgb.Run() + return pgb +} \ No newline at end of file diff --git a/vendor/git.jiaxianghudong.com/go/utils/regexp.go b/vendor/git.jiaxianghudong.com/go/utils/regexp.go new file mode 100644 index 0000000..170776f --- /dev/null +++ b/vendor/git.jiaxianghudong.com/go/utils/regexp.go @@ -0,0 +1,89 @@ +package utils + +import ( + // "log" + "regexp" +) + +const ( + regUsername = `^[a-zA-Z0-9_]{4,22}$` + regPwd = `^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{3,60}$` + regNickname = `^{0,40}$` + regEmail = `^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$` + regPhone = `^((\d3)|(\d{3}\-))?13[0-9]\d{8}|14[0-9]\d{8}|15[0-9]\d{8}|17[0-9]\d{8}|18[0-9]\d{8}` + regUrl = `^((https?|ftp|news|http):\/\/)?([a-z]([a-z0-9\-]*[\.。])+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-z][a-z0-9_]*)?$` + regGuid = `[a-zA-Z0-9-_]{0,40}` + regDescription = `^{0,64}$` + regOutTypeDescription = `^{0,20}$` + regMac = `^{0,40}$` + regTradeNo = `^[a-zA-Z0-9_-]{1,40}$` + regAttach = `^{0,127}$` +) + +func CheckString(data string, pat string) bool { + bFlag := false + reg := regexp.MustCompile(pat) + bFlag = reg.MatchString(data) + return bFlag +} + +// 检测用户名 +func CheckUserName(username string) bool { + return CheckString(username, regUsername) +} + +// 昵称 +func CheckNickname(nickname string) bool { + return CheckString(nickname, regNickname) + +} + +// 密码 +func CheckPwd(password string) bool { + return CheckString(password, regPwd) +} + +// 邮箱 +func CheckEmail(email string) bool { + return CheckString(email, regEmail) +} + +// 手机号 +func CheckPhone(phone string) bool { + return CheckString(phone, regPhone) +} + +// 网址 +func CheckUrl(url string) bool { + return CheckString(url, regUrl) +} + +// guid +func CheckGuid(guid string) bool { + return CheckString(guid, regGuid) +} + +// 描述 +func CheckDescription(description string) bool { + return CheckString(description, regDescription) +} + +// 平台交易类型描述 +func CheckOutTypeDescription(description string) bool { + return CheckString(description, regOutTypeDescription) +} + +// mac 地址 +func CheckMac(mac string) bool { + return CheckString(mac, regMac) +} + +// 订单号 +func CheckTradeNo(tradeNo string) bool { + return CheckString(tradeNo, regTradeNo) +} + +// 附加参数 +func CheckAttach(attach string) bool { + return CheckString(attach, regAttach) +} diff --git a/vendor/git.jiaxianghudong.com/go/utils/strip.go b/vendor/git.jiaxianghudong.com/go/utils/strip.go new file mode 100644 index 0000000..312d0bc --- /dev/null +++ b/vendor/git.jiaxianghudong.com/go/utils/strip.go @@ -0,0 +1,3713 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package utils +//package strip + +import ( + "bytes" + "encoding/json" + "fmt" + "html" + "io" + "io/ioutil" + "path/filepath" + "reflect" + "strings" + "sync" + "text/template" + "text/template/parse" + "unicode" + "unicode/utf8" +) + +// htmlNospaceEscaper escapes for inclusion in unquoted attribute values. +func htmlNospaceEscaper(args ...interface{}) string { + s, t := stringify(args...) + if t == contentTypeHTML { + return htmlReplacer(StripTags(s), htmlNospaceNormReplacementTable, false) + } + return htmlReplacer(s, htmlNospaceReplacementTable, false) +} + +// attrEscaper escapes for inclusion in quoted attribute values. +func attrEscaper(args ...interface{}) string { + s, t := stringify(args...) + if t == contentTypeHTML { + return htmlReplacer(StripTags(s), htmlNormReplacementTable, true) + } + return htmlReplacer(s, htmlReplacementTable, true) +} + +// rcdataEscaper escapes for inclusion in an RCDATA element body. +func rcdataEscaper(args ...interface{}) string { + s, t := stringify(args...) + if t == contentTypeHTML { + return htmlReplacer(s, htmlNormReplacementTable, true) + } + return htmlReplacer(s, htmlReplacementTable, true) +} + +// htmlEscaper escapes for inclusion in HTML text. +func htmlEscaper(args ...interface{}) string { + s, t := stringify(args...) + if t == contentTypeHTML { + return s + } + return htmlReplacer(s, htmlReplacementTable, true) +} + +// htmlReplacementTable contains the runes that need to be escaped +// inside a quoted attribute value or in a text node. +var htmlReplacementTable = []string{ + // http://www.w3.org/TR/html5/syntax.html#attribute-value-(unquoted)-state + // U+0000 NULL Parse error. Append a U+FFFD REPLACEMENT + // CHARACTER character to the current attribute's value. + // " + // and similarly + // http://www.w3.org/TR/html5/syntax.html#before-attribute-value-state + 0: "\uFFFD", + '"': """, + '&': "&", + '\'': "'", + '+': "+", + '<': "<", + '>': ">", +} + +// htmlNormReplacementTable is like htmlReplacementTable but without '&' to +// avoid over-encoding existing entities. +var htmlNormReplacementTable = []string{ + 0: "\uFFFD", + '"': """, + '\'': "'", + '+': "+", + '<': "<", + '>': ">", +} + +// htmlNospaceReplacementTable contains the runes that need to be escaped +// inside an unquoted attribute value. +// The set of runes escaped is the union of the HTML specials and +// those determined by running the JS below in browsers: +//
+// +var htmlNospaceReplacementTable = []string{ + 0: "�", + '\t': " ", + '\n': " ", + '\v': "", + '\f': "", + '\r': " ", + ' ': " ", + '"': """, + '&': "&", + '\'': "'", + '+': "+", + '<': "<", + '=': "=", + '>': ">", + // A parse error in the attribute value (unquoted) and + // before attribute value states. + // Treated as a quoting character by IE. + '`': "`", +} + +// htmlNospaceNormReplacementTable is like htmlNospaceReplacementTable but +// without '&' to avoid over-encoding existing entities. +var htmlNospaceNormReplacementTable = []string{ + 0: "�", + '\t': " ", + '\n': " ", + '\v': "", + '\f': "", + '\r': " ", + ' ': " ", + '"': """, + '\'': "'", + '+': "+", + '<': "<", + '=': "=", + '>': ">", + // A parse error in the attribute value (unquoted) and + // before attribute value states. + // Treated as a quoting character by IE. + '`': "`", +} + +// htmlReplacer returns s with runes replaced according to replacementTable +// and when badRunes is true, certain bad runes are allowed through unescaped. +func htmlReplacer(s string, replacementTable []string, badRunes bool) string { + written, b := 0, new(bytes.Buffer) + for i, r := range s { + if int(r) < len(replacementTable) { + if repl := replacementTable[r]; len(repl) != 0 { + b.WriteString(s[written:i]) + b.WriteString(repl) + // Valid as long as replacementTable doesn't + // include anything above 0x7f. + written = i + utf8.RuneLen(r) + } + } else if badRunes { + // No-op. + // IE does not allow these ranges in unquoted attrs. + } else if 0xfdd0 <= r && r <= 0xfdef || 0xfff0 <= r && r <= 0xffff { + fmt.Fprintf(b, "%s%x;", s[written:i], r) + written = i + utf8.RuneLen(r) + } + } + if written == 0 { + return s + } + b.WriteString(s[written:]) + return b.String() +} + +// stripTags takes a snippet of HTML and returns only the text content. +// For example, `¡Hi! ` -> `¡Hi! `. +func StripTags(html string) string { + var b bytes.Buffer + s, c, i, allText := []byte(html), context{}, 0, true + // Using the transition funcs helps us avoid mangling + // `