go语言渐入佳境-网络[16]-http

##获取网站内容

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
package main

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

func main(){

resp,err:= http.Get("http://www.zhenai.com/zhenghun")

if err!=nil{
panic(err)
}


defer resp.Body.Close()

if resp.StatusCode == http.StatusOK{
all,err:=ioutil.ReadAll(resp.Body)
if err!=nil{
panic(err)
}
fmt.Printf("%s\n",all)
}
}

当charset为gbk时,转换为utf-8

下载辅助包

gopm get -g -v golang.org/x/text
gopm get -g -v golang.org/x/net/html

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
package main

import (
"net/http"
"io/ioutil"
"fmt"
"io"
"golang.org/x/net/html/charset"
"golang.org/x/text/encoding"
"bufio"
"golang.org/x/text/transform"
)

func main(){

resp,err:= http.Get("http://www.chinanews.com/")

if err!=nil{
panic(err)
}


defer resp.Body.Close()
if resp.StatusCode != http.StatusOK{
fmt.Println("Error: status code",resp.StatusCode)
}
e:= determineEncoding(resp.Body)
utf8reader:= transform.NewReader(resp.Body,e.NewDecoder())

all,err:= ioutil.ReadAll(utf8reader)
if err!=nil{
panic(err)
}
fmt.Printf("%s\n",all)



}



func determineEncoding(r io.Reader) encoding.Encoding{
bytes,err := bufio.NewReader(r).Peek(1024)
if err !=nil{
panic(err)
}
e,_,_:= charset.DetermineEncoding(bytes,"")
return e
}

http服务器1

访问localhost:8000,打印出URL.Path = “/”

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

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

func main() {
http.HandleFunc("/", handler) // each request calls handler
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}

// handler echoes the Path component of the requested URL.
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
}

http服务器2

计数:

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
package main

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

var mu sync.Mutex
var count int

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

// handler echoes the Path component of the requested URL.
func handler(w http.ResponseWriter, r *http.Request) {
mu.Lock()
count++
mu.Unlock()
fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
}

// counter echoes the number of calls so far.
func counter(w http.ResponseWriter, r *http.Request) {
mu.Lock()
fmt.Fprintf(w, "Count %d\n", count)
mu.Unlock()
}

http服务器2

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
package main

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

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

//!+handler
// handler echoes the HTTP request.
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s %s %s\n", r.Method, r.URL, r.Proto)
for k, v := range r.Header {
fmt.Fprintf(w, "Header[%q] = %q\n", k, v)
}
fmt.Fprintf(w, "Host = %q\n", r.Host)
fmt.Fprintf(w, "RemoteAddr = %q\n", r.RemoteAddr)
if err := r.ParseForm(); err != nil {
log.Print(err)
}
for k, v := range r.Form {
fmt.Fprintf(w, "Form[%q] = %q\n", k, v)
}
}

输出:

1
2
3
4
5
6
7
8
9
10
11
GET / HTTP/1.1
Header["Connection"] = ["keep-alive"]
Header["Upgrade-Insecure-Requests"] = ["1"]
Header["User-Agent"] = ["Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"]
Header["Accept-Encoding"] = ["gzip, deflate, br"]
Header["Cookie"] = ["_ga=GA1.1.809627859.1535126425; io=nukCk_cXUcwmTK_-AAAC"]
Header["Cache-Control"] = ["max-age=0"]
Header["Accept"] = ["text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"]
Header["Accept-Language"] = ["zh-CN,zh;q=0.9"]
Host = "localhost:8000"
RemoteAddr = "127.0.0.1:56512"

http文件服务器

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
/* File Server
*/

package main

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

func main() {
// deliver files from the directory /var/www
//fileServer := http.FileServer(http.Dir("/var/www"))
fileServer := http.FileServer(http.Dir("/Users/jackson/"))

// register the handler and deliver requests to it
err := http.ListenAndServe(":8000", fileServer)
checkError(err)
// That's it!
}

func checkError(err error) {
if err != nil {
fmt.Println("Fatal error ", err.Error())
os.Exit(1)
}
}