文章目录
  1. 1. Socket编程
    1. 1.1. Client Side
    2. 1.2. Server Side
  2. 2. Http编程
    1. 2.1. Client Side
    2. 2.2. Server Side
      1. 2.2.1. http请求
      2. 2.2.2. https请求
      3. 2.2.3. 模板缓存
      4. 2.2.4. 动态请求和静态分离
  3. 3. 资料

Go网络编程

Socket编程

Client Side

func Dial (net, addr string) (Conn, error)

1
2
3
4
5
6
7
8
//TCP
conn, err := net.Dial ("tcp", "192.168.0.1:9000")

//UDP
conn, err := net.Dial ("udp", "192.168.0.1:9000")

//ICMP
conn, err := net.Dial ("ip4.icmp", "192.168.0.1:9000")

Server Side

func Listen(net, laddr string) (l Listener, err os.Error)

1
2
3
4
5
6
service := ":1200"
//TCP
conn, err := net.Listen("tcp", service)

//UDP
conn, err := net.Listen ("udp", service)

I THINK: It is cool !


Http编程

Client Side

func (c *Client) Get (url string) (r *Response, err error)
func (c *Client) Post (url string, bodyType string, body io.Reader) (r *Response, err error)
func (c *Client) PostForm (url string, data url.Values) (r *Respone, err error)
func (c *Client) Head (url, string) (r *Response, err error)
func (c *Client) Do (request *Requset) (resp *Response, err error)

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() {
    client := &http.Client{}
    reqest, _ := http.NewRequest("GET", "http://www.baidu.com", nil)
     
    reqest.Header.Set("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
    reqest.Header.Set("Accept-Charset","GBK,utf-8;q=0.7,*;q=0.3")
    reqest.Header.Set("Accept-Encoding","gzip,deflate,sdch")
    reqest.Header.Set("Accept-Language","zh-CN,zh;q=0.8")
    reqest.Header.Set("Cache-Control","max-age=0")
    reqest.Header.Set("Connection","keep-alive")
     
    response,_ := client.Do(reqest)
    if response.StatusCode == 200 {
        body, _ := ioutil.ReadAll(response.Body)
        bodystr := string(body);
        fmt.Println(bodystr)
    }
}

Client Side代码来源网络

Server Side

net.Listen

http请求

func ListenAndServe(addr string, handler Handler) error

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

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

func helloWorld (w http.ResponseWriter, r *http.Request) {
	io.WriteString (w, "Hello World")
}

func main () {
	http.HandleFunc ("/hello", helloWorld)
	err := http.ListenAndServe(":8099", nil)
	if err != nil {
		log.Fatal(" ListenAndServe: ", err.Error())
	}	
}

https请求

func ListenAndServeTLS(addr string, handler Handler) error

模板缓存

这个有必要单独出来,是做逻辑与页面分离的。
templates := make(map[string]*template.Template)

动态请求和静态分离

需要自己写个Handler函数,好烂


总结
Socket 喜欢!
Http 对于习惯Java 编程的我,不喜欢!

资料

  1. Network programming with Go, really helpful !!!
  2. Go Project
文章目录
  1. 1. Socket编程
    1. 1.1. Client Side
    2. 1.2. Server Side
  2. 2. Http编程
    1. 2.1. Client Side
    2. 2.2. Server Side
      1. 2.2.1. http请求
      2. 2.2.2. https请求
      3. 2.2.3. 模板缓存
      4. 2.2.4. 动态请求和静态分离
  3. 3. 资料