go编程之常见工具函数
1、时间格式化
基于模式的布局进行时间格式化和解析
package main import "fmt"
import "time" func main() {
p := fmt.Println t := time.Now()
p(t.Format(time.RFC3339)) t1, e := time.Parse(
time.RFC3339,
"2012-11-01T22:08:41+00:00")
p(t1) p(t.Format("3:04PM"))
p(t.Format("Mon Jan _2 15:04:05 2006"))
p(t.Format("2006-01-02T15:04:05.999999-07:00"))
form := "3 04 PM"
t2, e := time.Parse(form, "8 41 PM")
p(t2) fmt.Printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second()) ansic := "Mon Jan _2 15:04:05 2006"
_, e = time.Parse(ansic, "8:41PM")
p(e)
}
执行上面代码,将得到以下输出结果
--23T11::+:
-- :: + +
:41AM
Thu Mar ::
--23T11::52.246508+:
-- :: + UTC
--23T11::-:
parsing time "8:41PM" as "Mon Jan _2 15:04:05 2006": cannot parse "8:41PM" as "Mon"
2、字符串格式化
package main import "fmt"
import "os" type point struct {
x, y int
} func main() {
p := point{, }
fmt.Printf("%v\n", p) fmt.Printf("%+v\n", p) fmt.Printf("%#v\n", p) fmt.Printf("%T\n", p) fmt.Printf("%t\n", true) fmt.Printf("%d\n", ) fmt.Printf("%b\n", ) fmt.Printf("%c\n", ) fmt.Printf("%x\n", ) fmt.Printf("%f\n", 78.9) fmt.Printf("%e\n", 123400000.0)
fmt.Printf("%E\n", 123400000.0) fmt.Printf("%s\n", "\"string\"") fmt.Printf("%q\n", "\"string\"") fmt.Printf("%x\n", "hex this") fmt.Printf("%p\n", &p) fmt.Printf("|%6d|%6d|\n", , ) fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45) fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45) fmt.Printf("|%6s|%6s|\n", "foo", "b") fmt.Printf("|%-6s|%-6s|\n", "foo", "b") s := fmt.Sprintf("a %s", "string")
fmt.Println(s) fmt.Fprintf(os.Stderr, "an %s\n", "error")
}
{ }
{x: y:}
main.point{x:, y:}
main.point
true !
1c8
78.900000
1.234000e+08
1.234000E+08
"string"
"\"string\"" 0xc042004280
| | |
| 1.20| 3.45|
|1.20 |3.45 |
| foo| b|
|foo |b |
a string
an error
3、正则表达式
package main import "bytes"
import "fmt"
import "regexp" func main() { // This tests whether a pattern matches a string.
match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
fmt.Println(match) // Above we used a string pattern directly, but for
// other regexp tasks you'll need to `Compile` an
// optimized `Regexp` struct.
r, _ := regexp.Compile("p([a-z]+)ch") // Many methods are available on these structs. Here's
// a match test like we saw earlier.
fmt.Println(r.MatchString("peach")) // This finds the match for the regexp.
fmt.Println(r.FindString("peach punch")) // This also finds the first match but returns the
// start and end indexes for the match instead of the
// matching text.
fmt.Println(r.FindStringIndex("peach punch")) // The `Submatch` variants include information about
// both the whole-pattern matches and the submatches
// within those matches. For example this will return
// information for both `p([a-z]+)ch` and `([a-z]+)`.
fmt.Println(r.FindStringSubmatch("peach punch")) // Similarly this will return information about the
// indexes of matches and submatches.
fmt.Println(r.FindStringSubmatchIndex("peach punch")) // The `All` variants of these functions apply to all
// matches in the input, not just the first. For
// example to find all matches for a regexp.
fmt.Println(r.FindAllString("peach punch pinch", -)) // These `All` variants are available for the other
// functions we saw above as well.
fmt.Println(r.FindAllStringSubmatchIndex(
"peach punch pinch", -)) // Providing a non-negative integer as the second
// argument to these functions will limit the number
// of matches.
fmt.Println(r.FindAllString("peach punch pinch", )) // Our examples above had string arguments and used
// names like `MatchString`. We can also provide
// `[]byte` arguments and drop `String` from the
// function name.
fmt.Println(r.Match([]byte("peach"))) // When creating constants with regular expressions
// you can use the `MustCompile` variation of
// `Compile`. A plain `Compile` won't work for
// constants because it has 2 return values.
r = regexp.MustCompile("p([a-z]+)ch")
fmt.Println(r) // The `regexp` package can also be used to replace
// subsets of strings with other values.
fmt.Println(r.ReplaceAllString("a peach", "<fruit>")) // The `Func` variant allows you to transform matched
// text with a given function.
in := []byte("a peach")
out := r.ReplaceAllFunc(in, bytes.ToUpper)
fmt.Println(string(out))
}
执行上面代码,将得到以下输出结果
true
true
peach
[ ]
[peach ea]
[ ]
[peach punch pinch]
[[ ] [ ] [ ]]
[peach punch]
true
p([a-z]+)ch
a <fruit>
a PEACH
4、Json
package main import "encoding/json"
import "fmt"
import "os" // We'll use these two structs to demonstrate encoding and
// decoding of custom types below.
type Response1 struct {
Page int
Fruits []string
}
type Response2 struct {
Page int `json:"page"`
Fruits []string `json:"fruits"`
} func main() { // First we'll look at encoding basic data types to
// JSON strings. Here are some examples for atomic
// values.
bolB, _ := json.Marshal(true)
fmt.Println(string(bolB)) intB, _ := json.Marshal()
fmt.Println(string(intB)) fltB, _ := json.Marshal(2.34)
fmt.Println(string(fltB)) strB, _ := json.Marshal("gopher")
fmt.Println(string(strB)) // And here are some for slices and maps, which encode
// to JSON arrays and objects as you'd expect.
slcD := []string{"apple", "peach", "pear"}
slcB, _ := json.Marshal(slcD)
fmt.Println(string(slcB)) mapD := map[string]int{"apple": , "lettuce": }
mapB, _ := json.Marshal(mapD)
fmt.Println(string(mapB)) // The JSON package can automatically encode your
// custom data types. It will only include exported
// fields in the encoded output and will by default
// use those names as the JSON keys.
res1D := &Response1{
Page: ,
Fruits: []string{"apple", "peach", "pear"}}
res1B, _ := json.Marshal(res1D)
fmt.Println(string(res1B)) // You can use tags on struct field declarations
// to customize the encoded JSON key names. Check the
// definition of `Response2` above to see an example
// of such tags.
res2D := &Response2{
Page: ,
Fruits: []string{"apple", "peach", "pear"}}
res2B, _ := json.Marshal(res2D)
fmt.Println(string(res2B)) // Now let's look at decoding JSON data into Go
// values. Here's an example for a generic data
// structure.
byt := []byte(`{"num":6.13,"strs":["a","b"]}`) // We need to provide a variable where the JSON
// package can put the decoded data. This
// `map[string]interface{}` will hold a map of strings
// to arbitrary data types.
var dat map[string]interface{} // Here's the actual decoding, and a check for
// associated errors.
if err := json.Unmarshal(byt, &dat); err != nil {
panic(err)
}
fmt.Println(dat) // In order to use the values in the decoded map,
// we'll need to cast them to their appropriate type.
// For example here we cast the value in `num` to
// the expected `float64` type.
num := dat["num"].(float64)
fmt.Println(num) // Accessing nested data requires a series of
// casts.
strs := dat["strs"].([]interface{})
str1 := strs[].(string)
fmt.Println(str1) // We can also decode JSON into custom data types.
// This has the advantages of adding additional
// type-safety to our programs and eliminating the
// need for type assertions when accessing the decoded
// data.
str := `{"page": , "fruits": ["apple", "peach"]}`
res := Response2{}
json.Unmarshal([]byte(str), &res)
fmt.Println(res)
fmt.Println(res.Fruits[]) // In the examples above we always used bytes and
// strings as intermediates between the data and
// JSON representation on standard out. We can also
// stream JSON encodings directly to `os.Writer`s like
// `os.Stdout` or even HTTP response bodies.
enc := json.NewEncoder(os.Stdout)
d := map[string]int{"apple": , "lettuce": }
enc.Encode(d)
}
执行上面代码,将得到以下输出结果
true 2.34
"gopher"
["apple","peach","pear"]
{"apple":,"lettuce":}
{"Page":,"Fruits":["apple","peach","pear"]}
{"page":,"fruits":["apple","peach","pear"]}
map[num:6.13 strs:[a b]]
6.13
a
{ [apple peach]}
apple
{"apple":,"lettuce":}
5、数字解析
package main // The built-in package `strconv` provides the number
// parsing.
import "strconv"
import "fmt" func main() { // With `ParseFloat`, this `64` tells how many bits of
// precision to parse.
f, _ := strconv.ParseFloat("1.234", )
fmt.Println(f) // For `ParseInt`, the `0` means infer the base from
// the string. `64` requires that the result fit in 64
// bits.
i, _ := strconv.ParseInt("", , )
fmt.Println(i) // `ParseInt` will recognize hex-formatted numbers.
d, _ := strconv.ParseInt("0x1c8", , )
fmt.Println(d) // A `ParseUint` is also available.
u, _ := strconv.ParseUint("", , )
fmt.Println(u) // `Atoi` is a convenience function for basic base-10
// `int` parsing.
k, _ := strconv.Atoi("")
fmt.Println(k) // Parse functions return an error on bad input.
_, e := strconv.Atoi("wat")
fmt.Println(e)
}
执行上面代码,将得到以下输出结果
1.234 strconv.ParseInt: parsing "wat": invalid syntax
6、Url解析
package main import "fmt"
import "net"
import "net/url" func main() { s := "postgres://user:pass@host.com:5432/path?k=v#f" u, err := url.Parse(s)
if err != nil {
panic(err)
} fmt.Println(u.Scheme) fmt.Println(u.User)
fmt.Println(u.User.Username())
p, _ := u.User.Password()
fmt.Println(p) fmt.Println(u.Host)
host, port, _ := net.SplitHostPort(u.Host)
fmt.Println(host)
fmt.Println(port) fmt.Println(u.Path)
fmt.Println(u.Fragment) fmt.Println(u.RawQuery)
m, _ := url.ParseQuery(u.RawQuery)
fmt.Println(m)
fmt.Println(m["k"][])
}
执行上面代码,将得到以下输出结果
postgres
user:pass
user
pass
host.com:
host.com /path
f
k=v
map[k:[v]]
v
7、SHA1哈希
package main // Go implements several hash functions in various
// `crypto/*` packages.
import "crypto/sha1"
import "fmt" func main() {
s := "sha1 this string"//原始字符串 h := sha1.New()//加密对象 h.Write([]byte(s))//将原始字符串转换成字节切片传给加密对象 bs := h.Sum(nil)//哈希结果追加和片段 可以不需要 fmt.Println(s)//打印原始字符串
fmt.Printf("%x\n", bs)//输出哈希结果
}
执行上面代码,将得到以下输出结果
sha1 this string
cf23df2207d99a74fbe169e3eba035e633b65d94
8、Base64编码
Go提供对base64
编码/解码的内置支持。导入带有b64
名称的encoding/base64
软件包,而不是默认的base64
。它会节省我们一些空间。编码器需要一个[]byte
,所以将字符串转换为该类型。
import b64 "encoding/base64"
import "fmt" func main() {
data := "abc123!?$*&()'-=@~" sEnc := b64.StdEncoding.EncodeToString([]byte(data))
fmt.Println(sEnc) sDec, _ := b64.StdEncoding.DecodeString(sEnc)
fmt.Println(string(sDec))
fmt.Println() uEnc := b64.URLEncoding.EncodeToString([]byte(data))
fmt.Println(uEnc)
uDec, _ := b64.URLEncoding.DecodeString(uEnc)
fmt.Println(string(uDec))
}
执行上面代码,将得到以下输出结果
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~ YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~
9、文件读写
读取和写入文件是许多Go
程序所需的基本任务。
1、读取文件
package main import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
)
//检查error状态 如果包含错误信息 则使用panic中断
func check(e error) {
if e != nil {
panic(e)
}
} func main() { dat, err := ioutil.ReadFile("/tmp/dat")//直接读取文件内容到内存
check(err)
fmt.Print(string(dat)) //使用os.Open打开文件 以获取文件的更多操作
f, err := os.Open("/tmp/dat")
check(err) b1 := make([]byte, )
n1, err := f.Read(b1)//读取5个字节
check(err)
fmt.Printf("%d bytes: %s\n", n1, string(b1)) o2, err := f.Seek(, )//定位到文件开头6个字符后
check(err)
b2 := make([]byte, )
n2, err := f.Read(b2)//读取2个字节
check(err)
fmt.Printf("%d bytes @ %d: %s\n", n2, o2, string(b2)) o3, err := f.Seek(, )
check(err)
b3 := make([]byte, )
n3, err := io.ReadAtLeast(f, b3, )//使用io对象读取
check(err)
fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3)) _, err = f.Seek(, )//定位到文件开始位置
check(err) r4 := bufio.NewReader(f)//bufio先读取到缓存
b4, err := r4.Peek()//然后从缓存中拿字节 比较高效
check(err)
fmt.Printf("5 bytes: %s\n", string(b4)) f.Close()
}
执行上面代码,将得到以下输出结果
abcdfawef!@
cawfe
awefawef awefaf
bytes: abcdf
bytes @ : we
bytes @ : we
bytes: abcdf
2、文件写入
package main import (
"bufio"
"fmt"
"io/ioutil"
"os"
) func check(e error) {
if e != nil {
panic(e)
}
} func main() {
d1 := []byte("hello\ngo\n")
err := ioutil.WriteFile("dat1.txt", d1, )
check(err) f, err := os.Create("dat2.txt")
check(err) defer f.Close()//延迟关闭文件操作(f超出作用域) d2 := []byte{, , , , }
n2, err := f.Write(d2)
check(err)
fmt.Printf("wrote %d bytes\n", n2) n3, err := f.WriteString("writes\n")
fmt.Printf("wrote %d bytes\n", n3) f.Sync() w := bufio.NewWriter(f)
n4, err := w.WriteString("buffered\n")
fmt.Printf("wrote %d bytes\n", n4) w.Flush()
}
10、行过滤器
package main import (
"bufio"//读写
"fmt"//格式化输出
"os"//操作系统
"strings"//字符串
) func main() {
scanner := bufio.NewScanner(os.Stdin)//扫描标准输入 for scanner.Scan() {
ucl := strings.ToUpper(scanner.Text())//标
fmt.Println(ucl)
} if err := scanner.Err(); err != nil {//发送错误 退出
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit()
}
}
11、环境变量
通过os包获取和设置环境变量
package main import "os"
import "strings"
import "fmt" func main() { // To set a key/value pair, use `os.Setenv`. To get a
// value for a key, use `os.Getenv`. This will return
// an empty string if the key isn't present in the
// environment.
os.Setenv("FOO", "")
fmt.Println("FOO:", os.Getenv("FOO"))
fmt.Println("BAR:", os.Getenv("BAR")) // Use `os.Environ` to list all key/value pairs in the
// environment. This returns a slice of strings in the
// form `KEY=value`. You can `strings.Split` them to
// get the key and value. Here we print all the keys.
fmt.Println()
for _, e := range os.Environ() {
pair := strings.Split(e, "=")
fmt.Println(pair[])
}
}
12、信号
信号通知通过在通道上发送os.Signal
值来工作。
package main import "fmt"
import "os"
import "os/signal"
import "syscall" func main() { sigs := make(chan os.Signal, )//信号通道
done := make(chan bool, ) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) go func() {
sig := <-sigs//等待信号
fmt.Println()
fmt.Println(sig)
done <- true//发送给done通道
}() fmt.Println("awaiting signal")
<-done//收到匿名函数发送的true值后 退出程序
fmt.Println("exiting")
}
执行上面代码,将得到以下输出结果
awaiting signal
[Ctl+C]
interrupt
exiting
go编程之常见工具函数的更多相关文章
- AJAX编程-封装ajax工具函数
即 Asynchronous [e'sɪŋkrənəs] Javascript And XML,AJAX 不是一门的新的语言,而是对现有技术的综合利用.本质是在HTTP协议的基础上以异步的方式与服务器 ...
- Python函数式编程(二):常见高级函数
一个函数的参数中有函数作为参数,这个函数就为高级函数. 下面学习几个常见高级函数. ---------------------------------------------------------- ...
- Android 常见工具类封装
1,MD5工具类: public class MD5Util { public final static String MD5(String s) { char hexDigits[] = { '0' ...
- jquery源码分析-工具函数
jQuery的版本一路狂飙啊,现在都到了2.0.X版本了.有空的时候,看看jquery的源码,学习一下别人的编程思路还是不错的. 下面这里是一些jquery的工具函数代码,大家可以看看,实现思路还是很 ...
- 从零开始学习jQuery (九) jQuery工具函数
一.摘要 本系列文章将带您进入jQuery的精彩世界, 其中有很多作者具体的使用经验和解决方案, 即使你会使用jQuery也能在阅读中发现些许秘籍. 我们经常要使用脚本处理各种业务逻辑, 最常见的就 ...
- 并行计算基础&编程模型与工具
在当前计算机应用中,对快速并行计算的需求是广泛的,归纳起来,主要有三种类型的应用需求: 计算密集(Computer-Intensive)型应用,如大型科学project计算与数值模拟: 数据密集(Da ...
- 封装一个Ajax工具函数
/*封装一个ajax工具函数*/ window.$ = {}; /*通过$定义一个ajax函数*/ /* * 1. type string 请求的方式 默认是get * 2. url ...
- 老李分享: 并行计算基础&编程模型与工具 2
2.并行编程模型和工具 – MPI – MPI(Message Passing Interface)是一种消息传递编程模型,服务于进程通信.它不特指某一个对它的实现,而是一种标准和规范的代表,它是一种 ...
- 老李分享: 并行计算基础&编程模型与工具
在当前计算机应用中,对高速并行计算的需求是广泛的,归纳起来,主要有三种类型的应用需求: 计算密集(Computer-Intensive)型应用,如大型科学工程计算与数值模拟: 数据密集(Data-In ...
随机推荐
- [线性筛]P1865 A % B Problem
题目背景 题目名称是吸引你点进来的 实际上该题还是很水的 题目描述 区间质数个数 输入输出格式 输入格式: 一行两个整数 询问次数n,范围m 接下来n行,每行两个整数 l,r 表示区间 输出格式: 对 ...
- 安卓自定义控件(二)BitmapShader、ShapeDrawable、Shape
第一篇博客中,我已经Canvas.Paint.Shader.Xfermode这些对象做了总结,而现在这篇文章主要介绍BitmapShader位图渲染,Xfermode如何实际应用,还有形状的绘制.不过 ...
- centos6.5 短信猫部署发短信
本文为在centos下部署短信猫发短信使用,以下为具体环境和步骤说明,欢迎留言! 一.环境说明 服务器:centos6.5 x64 依赖包:lockdev-1.0.1-18.el6.x86_64.rp ...
- hadoop2.5的伪分布式安装配置
一.windows环境下安装 根据博主写的一次性安装成功了: http://blog.csdn.net/antgan/article/details/52067441 二.linux环境下(cento ...
- 【译】10个机器学习的JavaScript示例
原文地址:10 Machine Learning Examples in JavaScript 在过去的每一年,用于机器学习(Machine Learning)的库在变得越来越快和易用.一直以来Pyt ...
- python爬虫实战 获取豆瓣排名前250的电影信息--基于正则表达式
一.项目目标 爬取豆瓣TOP250电影的评分.评价人数.短评等信息,并在其保存在txt文件中,html解析方式基于正则表达式 二.确定页面内容 爬虫地址:https://movie.douban.co ...
- Smarty基础用法
一.Smarty基础用法: 1.基础用法如下 include './smarty/Smarty.class.php';//引入smarty类 $smarty = new Smarty();//实例化s ...
- redis秒杀
用Redis轻松实现秒杀系统 秒杀系统的架构设计 秒杀系统,是典型的短时大量突发访问类问题.对这类问题,有三种优化性能的思路: 写入内存而不是写入硬盘 异步处理而不是同步处理 分布式处理 用上这三招, ...
- 浅谈php的优缺点
一.优点 1. 跨平台,性能优越,跟Linux/Unix结合别跟Windows结合性能强45%,并且和很多免费的平台结合非常省钱,比如LAMP(Linux /Apache/Mysql/PHP)或者FA ...
- node.js爬虫
这是一个简单的node.js爬虫项目,麻雀虽小五脏俱全. 本项目主要包含一下技术: 发送http抓取页面(http).分析页面(cheerio).中文乱码处理(bufferhelper).异步并发流程 ...