Golang实践:HelloWorld

发布于 2017-08-29 · 本文总共 4110 字 · 阅读大约需要 12 分钟

hello, world

package main

import "fmt"

func main()  {
	fmt.Println("Hello, World!")
}

go run将一个或者多个以.go为后缀的源文件进行编译、链接,然后运行生成的可执行文件;

go run helloworld.go
% go run helloworld.go 
Hello, World!

Go原生的支持Unicode,可以处理所有国家的语言;

package main

import "fmt"

func main()  {
	fmt.Println("Hello, World!")
	fmt.Println("你好, 世界!")
}

go run:

% go run helloworld.go 
Hello, World!
你好, 世界!

go build编译成可执行文件:

go build  helloworld.go 
./helloworld
Hello, World!
你好, 世界!

Printf函数转义字符

verb 描述
%d 十进制整数
%x,%o,%b 十六进制、八进制、二进制
%f,%g,%e 浮点数
%t 布尔类型
%c 字符
%s 字符串
%q 带引号字符串
%v 内置格式的任何值
%T 任何值的类型
%% 百分号

实践:命令行参数

package main

import (
	"fmt"
	"os"
)

func main() {
	s := ""
	seq := ""
	for i := 1; i < len(os.Args); i++ {
		s += seq + os.Args[i]
		seq = " "
	}
	fmt.Println(s)
}

go run:

./command hello world
hello world

使用strings.Join:

package main

import (
	"fmt"
	"os"
	"strings"
)

func main() {
	fmt.Println(strings.Join(os.Args[1:], " "))
}

实践:找出重复行

模仿uniq命令,写一个程序找出输入的重复行:

$ cat test.txt 
hello
hello
h
1
2
3
$ cat test.txt|uniq
hello
h
1
2
3

标准输入

dup:

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	Dup()
}

func Dup() {
	counts := make(map[string]int)
	input := bufio.NewScanner(os.Stdin)
	for input.Scan() {
		counts[input.Text()]++
	}

	for line, n := range counts {
		if n > 1 {
			fmt.Printf("%d\t%s\n", n, line)
		}
	}

}

dup

go build dup.go
cat test.txt | ./dup 
true hello

从文件读取

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	DupLinesInFiles()
}

func DupLinesInFiles() {
	counts := make(map[string]int)
	files := os.Args[1:]
	if len(files) == 0 {
		return
	} else {
		for _, file := range files {
			fp, err := os.Open(file)
			if err != nil {
				fmt.Fprintf(os.Stderr, "dup lines in file %s, error: %v\n", file, err)
				continue
			}
			countLines(fp, counts)
			fp.Close()
		}
	}
	for line, n := range counts {
		if n > 1 {
			fmt.Printf("%d\t%s\n", n, line)
		}
	}
}

func countLines(f *os.File, counts map[string]int) {
	input := bufio.NewScanner(f)
	for input.Scan() {
		counts[input.Text()]++
	}

}

cp test.txt test1.txt

./dup1 test.txt 
2	hello

./dup1 test.txt test1.txt 
2	2
2	3
4	hello
2	h
2	1

使用ioutil.ReadFile

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

func DupLinesInFiles1() {

	counts := make(map[string]int)
	for _, file := range os.Args[1:] {
		data, err := ioutil.ReadFile(file)
		if err != nil {
			fmt.Fprintf(os.Stderr, "dup lines in file %s, error: %v\n", file, err)
			continue
		}
		for _, line := range strings.Split(string(data), "\n") {
			counts[line]++
		}
	}

	for line, n := range counts {
		if n > 1 {
			fmt.Printf("%d\t%s\n", n, line)
		}
	}
}

func main() {

	DupLinesInFiles1()

}

实践:并发获取URL

fetch.go

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
)

func main() {

	for _, url := range os.Args[1:] {
		resp, err := http.Get(url)
		if err != nil {
			fmt.Fprintf(os.Stderr, "get url (%s) error: %s\n", url, err.Error())
			os.Exit(1)
		}
		if resp.Body != nil {
			defer resp.Body.Close()
			body, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				fmt.Fprintf(os.Stderr, "get url (%s) reading error: %s\n", url, err.Error())
				os.Exit(1)
			}
			fmt.Printf("%s", body)
		}
	}
}

go build fetch.go
./fetch http://localhost:8001
Get url PATH: /

并发

fetchall.go

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"time"
)

func fetch(url string, ch chan<- string) {
	start := time.Now()
	resp, err := http.Get(url)
	if err != nil {
		fmt.Fprintf(os.Stderr, "get url (%s) error: %s\n", url, err.Error())
		os.Exit(1)
	}
	if resp.Body == nil {
		fmt.Fprintf(os.Stderr, "get url (%s) error: %s\n", url, "response nil")
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Fprintf(os.Stderr, "get url (%s) reading error: %s\n", url, err.Error())
		os.Exit(1)
	}
	fmt.Printf("%s", body)
	ch <- fmt.Sprintf("%.6f seconds %7d %s", time.Since(start).Seconds(), len(body), url)

}

func main() {
	start := time.Now()
	ch := make(chan string)
	for _, url := range os.Args[1:] {
		go fetch(url, ch)
	}
	for range os.Args[1:] {
		fmt.Println(<-ch)
	}

	fmt.Printf("%.6f secondes elapsed\n", time.Since(start).Seconds())
}

go run fetchall.go

./fetchall http://localhost:8001 http://www.baidu.com
0.002738 seconds      16 http://localhost:8001
0.088088 seconds  285479 http://www.baidu.com
0.088129 secondes elapsed

实践:实现一个简单web服务器

server.go

package main

import (
"fmt"
"log"
"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	// w.Write([]byte(r.URL.Path))
	fmt.Fprintf(w, "Get url PATH: %s\n", r.URL.Path)
}

func main() {
	http.HandleFunc("/", handler)
	log.Fatal(http.ListenAndServe("localhost:8001", nil))
}

go build server.go ./server &

curl localhost:8001/
Get url PATH: /

refs

《The Go Programming Language》Alan A.A, Donovan & Brian W.Kernighan




本博客所有文章采用的授权方式为 自由转载-非商用-非衍生-保持署名 ,转载请务必注明出处,谢谢。
声明:
本博客欢迎转发,但请保留原作者信息!
博客地址:邱文奇(qiuwenqi)的博客;
内容系本人学习、研究和总结,如有雷同,实属荣幸!
阅读次数:

文章评论

comments powered by Disqus


章节列表