Files
leanote/app/lea/netutil/NetUtil.go

102 lines
1.7 KiB
Go
Raw Normal View History

2014-05-07 13:06:24 +08:00
package netutil
2015-11-13 17:58:41 +08:00
2014-05-07 13:06:24 +08:00
import (
"os"
2015-11-13 17:58:41 +08:00
"strings"
// "path/filepath"
. "github.com/leanote/leanote/app/lea"
"io/ioutil"
2014-11-09 16:24:19 +08:00
"net"
2014-05-07 13:06:24 +08:00
"net/http"
)
// net的util
// toPath 文件保存的目录
// 默认是/tmp
// 返回文件的完整目录
2014-10-22 16:20:45 +08:00
func WriteUrl(url string, toPath string) (length int64, newFilename, path string, ok bool) {
2014-05-07 13:06:24 +08:00
if url == "" {
2015-11-13 17:58:41 +08:00
return
2014-05-07 13:06:24 +08:00
}
content, err := GetContent(url)
if err != nil {
2015-11-13 17:58:41 +08:00
return
2014-05-07 13:06:24 +08:00
}
2015-11-13 17:58:41 +08:00
2014-10-22 16:20:45 +08:00
length = int64(len(content))
2015-11-13 17:58:41 +08:00
2014-05-07 13:06:24 +08:00
// a.html?a=a11&xxx
url = trimQueryParams(url)
_, ext := SplitFilename(url)
if toPath == "" {
toPath = "/tmp"
}
2015-11-13 17:58:41 +08:00
// dir := filepath.Dir(toPath)
2014-10-22 16:20:45 +08:00
newFilename = NewGuid() + ext
2014-05-07 13:06:24 +08:00
fullPath := toPath + "/" + newFilename
2015-11-13 17:58:41 +08:00
2014-05-07 13:06:24 +08:00
// 写到文件中
file, err := os.Create(fullPath)
2015-11-13 17:58:41 +08:00
defer file.Close()
if err != nil {
return
2014-05-07 13:06:24 +08:00
}
file.Write(content)
2015-11-13 17:58:41 +08:00
2014-05-07 13:06:24 +08:00
path = fullPath
ok = true
return
}
// 得到内容
func GetContent(url string) (content []byte, err error) {
var resp *http.Response
resp, err = http.Get(url)
2015-11-13 17:58:41 +08:00
if resp != nil && resp.Body != nil {
2014-05-07 13:06:24 +08:00
defer resp.Body.Close()
} else {
}
2015-11-13 17:58:41 +08:00
if resp == nil || resp.Body == nil || err != nil || resp.StatusCode != http.StatusOK {
2014-05-07 13:06:24 +08:00
return
2015-11-13 17:58:41 +08:00
}
var buf []byte
buf, err = ioutil.ReadAll(resp.Body)
if err != nil {
2014-05-07 13:06:24 +08:00
return
}
2015-11-13 17:58:41 +08:00
content = buf
err = nil
return
2014-05-07 13:06:24 +08:00
}
// 将url ?, #后面的字符串去掉
func trimQueryParams(url string) string {
2015-11-13 17:58:41 +08:00
pos := strings.Index(url, "?")
2014-05-07 13:06:24 +08:00
if pos != -1 {
2015-11-13 17:58:41 +08:00
url = Substr(url, 0, pos)
2014-05-07 13:06:24 +08:00
}
2015-11-13 17:58:41 +08:00
pos = strings.Index(url, "#")
2014-05-07 13:06:24 +08:00
if pos != -1 {
2015-11-13 17:58:41 +08:00
url = Substr(url, 0, pos)
2014-05-07 13:06:24 +08:00
}
2015-11-13 17:58:41 +08:00
pos = strings.Index(url, "!")
2014-05-07 13:06:24 +08:00
if pos != -1 {
2015-11-13 17:58:41 +08:00
url = Substr(url, 0, pos)
2014-05-07 13:06:24 +08:00
}
2015-11-13 17:58:41 +08:00
return url
2014-11-09 16:24:19 +08:00
}
// 通过domain得到ip
func GetIpFromDomain(domain string) string {
ip, _ := net.LookupIP(domain)
if ip != nil && len(ip) > 0 {
return ip[0].String()
}
return ""
2015-11-13 17:58:41 +08:00
}