Mark blog

知行合一 划水归档

Go 语言简介(四)

定时器

Go语言中可以使用time.NewTimer或time.NewTicker来设置一个定时器,这个定时器会绑定在你的当前channel中,通过channel的阻塞通知机器来通知你的程序。

下面是一个timer的示例。

1
2
3
4
5
6
7
8
9
10
11
package main

import "time"
import "fmt"

func main() {
timer := time.NewTimer(2*time.Second)

<- timer.C
fmt.Println("timer expired!")
}

上面的例程看起来像一个Sleep,是的,不过Timer是可以Stop的。你需要注意Timer只通知一次。如果你要像C中的Timer能持续通知的话,你需要使用Ticker。下面是Ticker的例程:

1
2
3
4
5
6
7
8
9
10
11
12
package main

import "time"
import "fmt"

func main() {
ticker := time.NewTicker(time.Second)

for t := range ticker.C {
fmt.Println("Tick at", t)
}
}

上面的这个ticker会让你程序进入死循环,我们应该放其放在一个goroutine中。下面这个程序结合了timer和ticker

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main

import "time"
import "fmt"

func main() {

ticker := time.NewTicker(time.Second)

go func () {
for t := range ticker.C {
fmt.Println(t)
}
}()

//设置一个timer,10钞后停掉ticker
timer := time.NewTimer(10*time.Second)
<- timer.C

ticker.Stop()
fmt.Println("timer expired!")
}

Socket编程

下面是我尝试的一个Echo Server的Socket代码,感觉还是挺简单的。

SERVER端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main

import (
"net"
"fmt"
"io"
)

const RECV_BUF_LEN = 1024

func main() {
listener, err := net.Listen("tcp", "0.0.0.0:6666")//侦听在6666端口
if err != nil {
panic("error listening:"+err.Error())
}
fmt.Println("Starting the server")

for {
conn, err := listener.Accept() //接受连接
if err != nil {
panic("Error accept:"+err.Error())
}
fmt.Println("Accepted the Connection :", conn.RemoteAddr())
go EchoServer(conn)
}
}

func EchoServer(conn net.Conn) {
buf := make([]byte, RECV_BUF_LEN)
defer conn.Close()

for {
n, err := conn.Read(buf);
switch err {
case nil:
conn.Write( buf[0:n] )
case io.EOF:
fmt.Printf("Warning: End of data: %s \n", err);
return
default:
fmt.Printf("Error: Reading data : %s \n", err);
return
}
}
}

CLIENT端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package main

import (
"fmt"
"time"
"net"
)

const RECV_BUF_LEN = 1024

func main() {
conn,err := net.Dial("tcp", "127.0.0.1:6666")
if err != nil {
panic(err.Error())
}
defer conn.Close()

buf := make([]byte, RECV_BUF_LEN)

for i := 0; i < 5; i++ {
//准备要发送的字符串
msg := fmt.Sprintf("Hello World, %03d", i)
n, err := conn.Write([]byte(msg))
if err != nil {
println("Write Buffer Error:", err.Error())
break
}
fmt.Println(msg)

//从服务器端收字符串
n, err = conn.Read(buf)
if err !=nil {
println("Read Buffer Error:", err.Error())
break
}
fmt.Println(string(buf[0:n]))

//等一秒钟
time.Sleep(time.Second)
}
}

系统调用

Go语言那么C,所以,一定会有一些系统调用。Go语言主要是通过两个包完成的。一个是os包,一个是syscall包。(注意,链接被墙)

这两个包里提供都是Unix-Like的系统调用,

  • syscall里提供了什么Chroot/Chmod/Chmod/Chdir…,Getenv/Getgid/Getpid/Getgroups/Getpid/Getppid…,还有很多如Inotify/Ptrace/Epoll/Socket/…的系统调用。
  • os包里提供的东西不多,主要是一个跨平台的调用。它有三个子包,Exec(运行别的命令), Signal(捕捉信号)和User(通过uid查name之类的)

syscall包的东西我不举例了,大家可以看看《Unix高级环境编程》一书。

os里的取几个例:

环境变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import "os"
import "strings"


func main() {
os.Setenv("WEB", "https://coolshell.cn") //设置环境变量
println(os.Getenv("WEB")) //读出来

for _, env := range os.Environ() { //穷举环境变量
e := strings.Split(env, "=")
println(e[0], "=", e[1])
}
}

执行命令行

下面是一个比较简单的示例

1
2
3
4
5
6
7
8
9
10
11
12
package main
import "os/exec"
import "fmt"
func main() {
cmd := exec.Command("ping", "127.0.0.1")
out, err := cmd.Output()
if err!=nil {
println("Command Error!", err.Error())
return
}
fmt.Println(string(out))
}

正规一点的用来处理标准输入和输出的示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
"strings"
"bytes"
"fmt"
"log"
"os/exec"
)

func main() {
cmd := exec.Command("tr", "a-z", "A-Z")
cmd.Stdin = strings.NewReader("some input")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
fmt.Printf("in all caps: %q\n", out.String())
}

命令行参数

Go语言中处理命令行参数很简单:(使用os的Args就可以了)

1
2
3
4
5
func main() {
args := os.Args
fmt.Println(args) //带执行文件的
fmt.Println(args[1:]) //不带执行文件的
}

在Windows下,如果运行结果如下:

1
2
C:\Projects\Go>go run args.go aaa bbb ccc ddd[C:\Users\haoel\AppData\Local\Temp\go-build742679827\command-line-arguments\_obj\a.out.exe aaa bbb ccc ddd]
[aaa bbb ccc ddd]

那么,如果我们要搞出一些像 mysql -uRoot -hLocalhost -pPwd 或是像 cc -O3 -Wall -o a a.c 这样的命令行参数我们怎么办?Go提供了一个package叫flag可以容易地做到这一点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main
import "flag"
import "fmt"

func main() {

//第一个参数是“参数名”,第二个是“默认值”,第三个是“说明”。返回的是指针
host := flag.String("host", "coolshell.cn", "a host name ")
port := flag.Int("port", 80, "a port number")
debug := flag.Bool("d", false, "enable/disable debug mode")

//正式开始Parse命令行参数
flag.Parse()

fmt.Println("host:", *host)
fmt.Println("port:", *port)
fmt.Println("debug:", *debug)
}

执行起来会是这个样子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#如果没有指定参数名,则使用默认值
$ go run flagtest.go
host: coolshell.cn
port: 80
debug: false

#指定了参数名后的情况
$ go run flagtest.go -host=localhost -port=22 -d
host: localhost
port: 22
debug: true

#用法出错了(如:使用了不支持的参数,参数没有=)
$ go build flagtest.go
$ ./flagtest -debug -host localhost -port=22
flag provided but not defined: -debug
Usage of flagtest:
-d=false: enable/disable debug mode
-host="coolshell.cn": a host name
-port=80: a port number
exit status 2

一个简单的HTTP Server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main

import (
"fmt"
"net/http"
"io/ioutil"
"path/filepath"
)

const http_root = "/home/haoel/coolshell.cn/"

func main() {
http.HandleFunc("/", rootHandler)
http.HandleFunc("/view/", viewHandler)
http.HandleFunc("/html/", htmlHandler)

http.ListenAndServe(":8080", nil)
}

//读取一些HTTP的头
func rootHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "rootHandler: %s\n", r.URL.Path)
fmt.Fprintf(w, "URL: %s\n", r.URL)
fmt.Fprintf(w, "Method: %s\n", r.Method)
fmt.Fprintf(w, "RequestURI: %s\n", r.RequestURI )
fmt.Fprintf(w, "Proto: %s\n", r.Proto)
fmt.Fprintf(w, "HOST: %s\n", r.Host)
}

//特别的URL处理
func viewHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "viewHandler: %s", r.URL.Path)
}

//一个静态网页的服务示例。(在http_root的html目录下)
func htmlHandler(w http.ResponseWriter, r *http.Request) {
fmt.Printf("htmlHandler: %s\n", r.URL.Path)

filename := http_root + r.URL.Path
fileext := filepath.Ext(filename)

content, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Printf(" 404 Not Found!\n")
w.WriteHeader(http.StatusNotFound)
return
}

var contype string
switch fileext {
case ".html", "htm":
contype = "text/html"
case ".css":
contype = "text/css"
case ".js":
contype = "application/javascript"
case ".png":
contype = "image/png"
case ".jpg", ".jpeg":
contype = "image/jpeg"
case ".gif":
contype = "image/gif"
default:
contype = "text/plain"
}
fmt.Printf("ext %s, ct = %s\n", fileext, contype)

w.Header().Set("Content-Type", contype)
fmt.Fprintf(w, "%s", content)

}

Go的功能库有很多,大家自己慢慢看吧。

参考自:

GO 语言简介(下)— 特性

https://coolshell.cn/articles/8489.html