站点更新:2018-01-23 15:49:21
This commit is contained in:
24
utils/date/formater.go
Normal file
24
utils/date/formater.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package date
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
const (
|
||||
YYYYMMDDHHmmSS = "2006-01-02 15:04:05"
|
||||
)
|
||||
|
||||
func Formater(formater string) string {
|
||||
r := ""
|
||||
for _, v := range formater {
|
||||
s := fmt.Sprintf("%c", v)
|
||||
switch s {
|
||||
case "y", "Y":
|
||||
r += s
|
||||
|
||||
case "-", " ":
|
||||
r += s
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
11
utils/date/formater_test.go
Normal file
11
utils/date/formater_test.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package date
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/ehlxr/go-utils/log"
|
||||
)
|
||||
|
||||
func TestDateFormater(t *testing.T) {
|
||||
log.Infof("now tims is %s", Formater("yyyy-MM-dd HH:mm:ss"))
|
||||
}
|
160
utils/ip/ip.go
Normal file
160
utils/ip/ip.go
Normal file
@@ -0,0 +1,160 @@
|
||||
package ip
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type IPInfo struct {
|
||||
Code int `json:"code"`
|
||||
Data IP `json:"data`
|
||||
}
|
||||
|
||||
type IP struct {
|
||||
Country string `json:"country"`
|
||||
CountryId string `json:"country_id"`
|
||||
Area string `json:"area"`
|
||||
AreaId string `json:"area_id"`
|
||||
Region string `json:"region"`
|
||||
RegionId string `json:"region_id"`
|
||||
City string `json:"city"`
|
||||
CityId string `json:"city_id"`
|
||||
Isp string `json:"isp"`
|
||||
}
|
||||
|
||||
func get_external() string {
|
||||
resp, err := http.Get("http://myexternalip.com/raw")
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
content, _ := ioutil.ReadAll(resp.Body)
|
||||
buf := new(bytes.Buffer)
|
||||
buf.ReadFrom(resp.Body)
|
||||
//s := buf.String()
|
||||
return string(content)
|
||||
}
|
||||
|
||||
func GetIntranetIp() {
|
||||
addrs, err := net.InterfaceAddrs()
|
||||
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
for _, address := range addrs {
|
||||
|
||||
// 检查ip地址判断是否回环地址
|
||||
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
|
||||
if ipnet.IP.To4() != nil {
|
||||
fmt.Println("ip:", ipnet.IP.String())
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TabaoAPI(ip string) *IPInfo {
|
||||
url := "http://ip.taobao.com/service/getIpInfo.php?ip="
|
||||
url += ip
|
||||
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
out, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var result IPInfo
|
||||
if err := json.Unmarshal(out, &result); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &result
|
||||
}
|
||||
|
||||
func inet_ntoa(ipnr int64) net.IP {
|
||||
var bytes [4]byte
|
||||
bytes[0] = byte(ipnr & 0xFF)
|
||||
bytes[1] = byte((ipnr >> 8) & 0xFF)
|
||||
bytes[2] = byte((ipnr >> 16) & 0xFF)
|
||||
bytes[3] = byte((ipnr >> 24) & 0xFF)
|
||||
|
||||
return net.IPv4(bytes[3], bytes[2], bytes[1], bytes[0])
|
||||
}
|
||||
|
||||
func inet_aton(ipnr net.IP) int64 {
|
||||
bits := strings.Split(ipnr.String(), ".")
|
||||
|
||||
b0, _ := strconv.Atoi(bits[0])
|
||||
b1, _ := strconv.Atoi(bits[1])
|
||||
b2, _ := strconv.Atoi(bits[2])
|
||||
b3, _ := strconv.Atoi(bits[3])
|
||||
|
||||
var sum int64
|
||||
|
||||
sum += int64(b0) << 24
|
||||
sum += int64(b1) << 16
|
||||
sum += int64(b2) << 8
|
||||
sum += int64(b3)
|
||||
|
||||
return sum
|
||||
}
|
||||
|
||||
func IpBetween(from net.IP, to net.IP, test net.IP) bool {
|
||||
if from == nil || to == nil || test == nil {
|
||||
fmt.Println("An ip input is nil") // or return an error!?
|
||||
return false
|
||||
}
|
||||
|
||||
from16 := from.To16()
|
||||
to16 := to.To16()
|
||||
test16 := test.To16()
|
||||
if from16 == nil || to16 == nil || test16 == nil {
|
||||
fmt.Println("An ip did not convert to a 16 byte") // or return an error!?
|
||||
return false
|
||||
}
|
||||
|
||||
if bytes.Compare(test16, from16) >= 0 && bytes.Compare(test16, to16) <= 0 {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func IsPublicIP(IP net.IP) bool {
|
||||
if IP.IsLoopback() || IP.IsLinkLocalMulticast() || IP.IsLinkLocalUnicast() {
|
||||
return false
|
||||
}
|
||||
if ip4 := IP.To4(); ip4 != nil {
|
||||
switch true {
|
||||
case ip4[0] == 10:
|
||||
return false
|
||||
case ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31:
|
||||
return false
|
||||
case ip4[0] == 192 && ip4[1] == 168:
|
||||
return false
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func GetPulicIP() string {
|
||||
conn, _ := net.Dial("udp", "8.8.8.8:80")
|
||||
defer conn.Close()
|
||||
localAddr := conn.LocalAddr().String()
|
||||
idx := strings.LastIndex(localAddr, ":")
|
||||
return localAddr[0:idx]
|
||||
}
|
58
utils/ip/ip_test.go
Normal file
58
utils/ip/ip_test.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package ip
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIp(t *testing.T) {
|
||||
|
||||
external_ip := get_external()
|
||||
|
||||
external_ip = strings.Replace(external_ip, "\n", "", -1)
|
||||
fmt.Println("公网ip是: ", external_ip)
|
||||
|
||||
fmt.Println("------Dividing Line------")
|
||||
|
||||
ip := net.ParseIP(external_ip)
|
||||
if ip == nil {
|
||||
fmt.Println("您输入的不是有效的IP地址,请重新输入!")
|
||||
} else {
|
||||
result := TabaoAPI(string(external_ip))
|
||||
if result != nil {
|
||||
fmt.Println("国家:", result.Data.Country)
|
||||
fmt.Println("地区:", result.Data.Area)
|
||||
fmt.Println("城市:", result.Data.City)
|
||||
fmt.Println("运营商:", result.Data.Isp)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println("------Dividing Line------GetIntranetIp")
|
||||
|
||||
GetIntranetIp()
|
||||
|
||||
fmt.Println("------Dividing Line------")
|
||||
|
||||
ip_int := inet_aton(net.ParseIP(external_ip))
|
||||
fmt.Println("Convert IPv4 address to decimal number(base 10) :", ip_int)
|
||||
|
||||
ip_result := inet_ntoa(ip_int)
|
||||
fmt.Println("Convert decimal number(base 10) to IPv4 address:", ip_result)
|
||||
|
||||
fmt.Println("------Dividing Line------")
|
||||
|
||||
is_between := IpBetween(net.ParseIP("0.0.0.0"), net.ParseIP("255.255.255.255"), net.ParseIP(external_ip))
|
||||
fmt.Println("check result: ", is_between)
|
||||
|
||||
fmt.Println("------Dividing Line------external_ip")
|
||||
is_public_ip := IsPublicIP(net.ParseIP(external_ip))
|
||||
fmt.Println("It is public ip: ", is_public_ip)
|
||||
|
||||
is_public_ip = IsPublicIP(net.ParseIP("169.254.85.131"))
|
||||
fmt.Println("It is public ip: ", is_public_ip)
|
||||
|
||||
fmt.Println("------Dividing Line------GetPulicIP")
|
||||
fmt.Println(GetPulicIP())
|
||||
}
|
54
utils/log/README.md
Normal file
54
utils/log/README.md
Normal file
@@ -0,0 +1,54 @@
|
||||
# log
|
||||
|
||||
golang log library base [logrus](https://github.com/sirupsen/logrus) and [logrus-prefixed-formatter](https://github.com/x-cray/logrus-prefixed-formatter)
|
||||
|
||||
# Usage
|
||||
|
||||
## 1. Use The glide Package Management
|
||||
|
||||
### install [glide](https://github.com/Masterminds/glide#install)
|
||||
|
||||
```bash
|
||||
$ go get github.com/Masterminds/glide
|
||||
|
||||
$ cd $GOPATH/src/github.com/Masterminds/glide
|
||||
|
||||
$ make setup
|
||||
```
|
||||
or
|
||||
|
||||
```bash
|
||||
# Mac OS
|
||||
$ brew install glide
|
||||
|
||||
# Mac or Linux
|
||||
$ curl https://glide.sh/get | sh
|
||||
```
|
||||
[Binary packages](https://github.com/Masterminds/glide/releases) are available for Mac, Linux and Windows.
|
||||
|
||||
### install log
|
||||
|
||||
```bash
|
||||
$ go get -u github.com/ehlxr/go-utils
|
||||
|
||||
$ cd $GOPATH/src/github.com/ehlxr/go-utils/log
|
||||
|
||||
$ glide install
|
||||
```
|
||||
|
||||
## 2. Manually add Dependencies
|
||||
|
||||
### add dependencies
|
||||
|
||||
```bash
|
||||
$ go get github.com/sirupsen/logrus
|
||||
$ go get github.com/x-cray/logrus-prefixed-formatter
|
||||
```
|
||||
|
||||
### install log
|
||||
|
||||
```bash
|
||||
$ go get -u github.com/ehlxr/go-utils
|
||||
```
|
||||
|
||||
|
240
utils/log/log.go
Normal file
240
utils/log/log.go
Normal file
@@ -0,0 +1,240 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/x-cray/logrus-prefixed-formatter"
|
||||
)
|
||||
|
||||
type (
|
||||
Fields logrus.Fields
|
||||
)
|
||||
|
||||
var (
|
||||
mylog *logrus.Logger
|
||||
fn bool //whether show file line
|
||||
)
|
||||
|
||||
func init() {
|
||||
mylog = logrus.New()
|
||||
mylog.Formatter = &logrus.JSONFormatter{}
|
||||
mylog.Out = os.Stdout
|
||||
mylog.Level = logrus.DebugLevel
|
||||
|
||||
mylog.Formatter = &prefixed.TextFormatter{
|
||||
ForceFormatting: true,
|
||||
QuoteEmptyFields: true,
|
||||
TimestampFormat: "2006-01-02 15:04:05",
|
||||
FullTimestamp: true,
|
||||
ForceColors: true,
|
||||
}
|
||||
|
||||
fn = true
|
||||
}
|
||||
|
||||
// whether show file line
|
||||
func SetFn(val bool) {
|
||||
fn = val
|
||||
}
|
||||
|
||||
func SetLogLevel(level logrus.Level) {
|
||||
mylog.Level = level
|
||||
}
|
||||
|
||||
func SetLogFormatter(formatter logrus.Formatter) {
|
||||
mylog.Formatter = formatter
|
||||
}
|
||||
|
||||
func NewLog(prefix string) *logrus.Entry {
|
||||
return mylog.WithField("prefix", prefix)
|
||||
}
|
||||
|
||||
func fileInfo(skip int) string {
|
||||
_, file, line, ok := runtime.Caller(skip)
|
||||
if !ok {
|
||||
file = "<???>"
|
||||
line = 1
|
||||
} else {
|
||||
slash := strings.LastIndex(file, "/")
|
||||
if slash >= 0 {
|
||||
file = file[slash+1:]
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("%s:%d", file, line)
|
||||
}
|
||||
|
||||
func Debug(args ...interface{}) {
|
||||
if fn {
|
||||
mylog.WithField("prefix", fileInfo(2)).Debug(args...)
|
||||
} else {
|
||||
mylog.Debug(args...)
|
||||
}
|
||||
}
|
||||
|
||||
func Debugf(format string, args ...interface{}) {
|
||||
if fn {
|
||||
mylog.WithField("prefix", fileInfo(2)).Debugf(format, args...)
|
||||
} else {
|
||||
mylog.Debugf(format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func DebugWithFields(fields Fields, args ...interface{}) {
|
||||
entry := mylog.WithFields(logrus.Fields(fields))
|
||||
|
||||
if fn {
|
||||
entry.Data["prefix"] = fileInfo(2)
|
||||
}
|
||||
entry.Debug(args...)
|
||||
}
|
||||
|
||||
func DebugfWithFields(fields Fields, format string, args ...interface{}) {
|
||||
entry := mylog.WithFields(logrus.Fields(fields))
|
||||
|
||||
if fn {
|
||||
entry.Data["prefix"] = fileInfo(2)
|
||||
}
|
||||
entry.Debugf(format, args...)
|
||||
}
|
||||
|
||||
func Info(args ...interface{}) {
|
||||
if fn {
|
||||
mylog.WithField("prefix", fileInfo(2)).Info(args...)
|
||||
} else {
|
||||
mylog.Info(args...)
|
||||
}
|
||||
}
|
||||
|
||||
func Infof(format string, args ...interface{}) {
|
||||
if fn {
|
||||
mylog.WithField("prefix", fileInfo(2)).Infof(format, args...)
|
||||
} else {
|
||||
mylog.Infof(format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func InfoWithFields(fields Fields, args ...interface{}) {
|
||||
entry := mylog.WithFields(logrus.Fields(fields))
|
||||
|
||||
if fn {
|
||||
entry.Data["prefix"] = fileInfo(2)
|
||||
}
|
||||
entry.Info(args...)
|
||||
|
||||
}
|
||||
|
||||
func InfofWithFields(fields Fields, format string, args ...interface{}) {
|
||||
entry := mylog.WithFields(logrus.Fields(fields))
|
||||
|
||||
if fn {
|
||||
entry.Data["prefix"] = fileInfo(2)
|
||||
}
|
||||
entry.Infof(format, args...)
|
||||
}
|
||||
|
||||
func Error(args ...interface{}) {
|
||||
if fn {
|
||||
mylog.WithField("prefix", fileInfo(2)).Error(args...)
|
||||
} else {
|
||||
mylog.Error(args...)
|
||||
}
|
||||
}
|
||||
|
||||
func Errorf(format string, args ...interface{}) {
|
||||
if fn {
|
||||
mylog.WithField("prefix", fileInfo(2)).Errorf(format, args...)
|
||||
} else {
|
||||
mylog.Errorf(format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func ErrorWithFields(fields Fields, args ...interface{}) {
|
||||
entry := mylog.WithFields(logrus.Fields(fields))
|
||||
|
||||
if fn {
|
||||
entry.Data["prefix"] = fileInfo(2)
|
||||
}
|
||||
entry.Error(args...)
|
||||
|
||||
}
|
||||
|
||||
func ErrorfWithFields(fields Fields, format string, args ...interface{}) {
|
||||
entry := mylog.WithFields(logrus.Fields(fields))
|
||||
|
||||
if fn {
|
||||
entry.Data["prefix"] = fileInfo(2)
|
||||
}
|
||||
entry.Errorf(format, args...)
|
||||
}
|
||||
|
||||
func Fatal(args ...interface{}) {
|
||||
if fn {
|
||||
mylog.WithField("prefix", fileInfo(2)).Fatal(args...)
|
||||
} else {
|
||||
mylog.Fatal(args...)
|
||||
}
|
||||
}
|
||||
|
||||
func Fatalf(format string, args ...interface{}) {
|
||||
if fn {
|
||||
mylog.WithField("prefix", fileInfo(2)).Fatalf(format, args...)
|
||||
} else {
|
||||
mylog.Fatalf(format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func FatalWithFields(fields Fields, args ...interface{}) {
|
||||
entry := mylog.WithFields(logrus.Fields(fields))
|
||||
|
||||
if fn {
|
||||
entry.Data["prefix"] = fileInfo(2)
|
||||
}
|
||||
entry.Fatal(args...)
|
||||
}
|
||||
|
||||
func FatalfWithFields(fields Fields, format string, args ...interface{}) {
|
||||
entry := mylog.WithFields(logrus.Fields(fields))
|
||||
|
||||
if fn {
|
||||
entry.Data["prefix"] = fileInfo(2)
|
||||
}
|
||||
entry.Fatalf(format, args...)
|
||||
}
|
||||
|
||||
func Panic(args ...interface{}) {
|
||||
if fn {
|
||||
mylog.WithField("prefix", fileInfo(2)).Panic(args...)
|
||||
} else {
|
||||
mylog.Panic(args...)
|
||||
}
|
||||
}
|
||||
|
||||
func Panicf(format string, args ...interface{}) {
|
||||
if fn {
|
||||
mylog.WithField("prefix", fileInfo(2)).Panicf(format, args...)
|
||||
} else {
|
||||
mylog.Panicf(format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func PanicWithFields(fields Fields, args ...interface{}) {
|
||||
entry := mylog.WithFields(logrus.Fields(fields))
|
||||
|
||||
if fn {
|
||||
entry.Data["prefix"] = fileInfo(2)
|
||||
}
|
||||
entry.Panic(args...)
|
||||
}
|
||||
|
||||
func PanicfWithFields(fields Fields, format string, args ...interface{}) {
|
||||
entry := mylog.WithFields(logrus.Fields(fields))
|
||||
|
||||
if fn {
|
||||
entry.Data["prefix"] = fileInfo(2)
|
||||
}
|
||||
entry.Panicf(format, args...)
|
||||
}
|
48
utils/log/log_test.go
Normal file
48
utils/log/log_test.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func TestSetting(t *testing.T) {
|
||||
SetFn(true)
|
||||
SetLogLevel(logrus.DebugLevel)
|
||||
SetLogFormatter(&logrus.JSONFormatter{TimestampFormat: "2006-01-02 15:04:05"})
|
||||
// SetLogFormatter(&prefixed.TextFormatter{
|
||||
// ForceFormatting: true,
|
||||
// QuoteEmptyFields: true,
|
||||
// TimestampFormat: "2006-01-02 15:04:05",
|
||||
// FullTimestamp: true,
|
||||
// ForceColors: true,
|
||||
// })
|
||||
}
|
||||
|
||||
func TestInfo(t *testing.T) {
|
||||
Info("this is a Info log test.")
|
||||
|
||||
InfoWithFields(Fields{
|
||||
"id": 10001,
|
||||
"name": "hello",
|
||||
}, "this is a InfoWithFields log test.")
|
||||
|
||||
Infof("this is a %s log test.", "Infof")
|
||||
|
||||
InfofWithFields(Fields{
|
||||
"id": 10001,
|
||||
"name": "hello",
|
||||
}, "this is a %s log test.", "InfofWithFields")
|
||||
}
|
||||
|
||||
func TestPanic(t *testing.T) {
|
||||
defer func() {
|
||||
if x := recover(); x != nil {
|
||||
fmt.Println("recover:", x)
|
||||
}
|
||||
}()
|
||||
Panic("this is a Panic log test.")
|
||||
|
||||
Panicf("this is a %s log test.", "Panicf")
|
||||
}
|
Reference in New Issue
Block a user