-
TCP Server / Client Development
net package provides network I / O development interface, including the TCP / the IP , the UDP , the DNS , and the Unix Domain Sockets .
Common development generally only need the most basic interface or function:
Server: net.Listen () , net.Accept ()
ln, err := net.Listen("tcp", ":8080") if err != nil { // handle error } for { conn, err := ln.Accept() if err != nil { // handle error } go handleConnection(conn) }
Client: net.Dial ()
conn, err := net.Dial("tcp", "golang.org:80") if err != nil { // handle error } fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n") status, err := bufio.NewReader(conn).ReadString('\n') // ...
Related API definitions:
func Listen(network, address string) (Listener, error) func (l *TCPListener) Accept() (Conn, error) func Dial(network, address string) (Conn, error)
-
web development
net / http package for eb provide support to develop, can very easily on the Web routing, static files, templates, the cookie data such as setup and operation.
Mainly two steps: set the access route, set the listening port.
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) func ListenAndServe(addr string, handler Handler) error func HFunc(w http.ResponseWriter, req *http.Request)
Example applications are as follows:
Import ( " FMT " " NET / HTTP " " strings " " log " ) FUNC main () { http.HandleFunc ( " / " , sayhelloName) // set access route ERR: = http.ListenAndServe ( " : 9090 " , nil ) // set the listen port IF ERR =! nil { log.Fatal ( " ListenAndServe: " , ERR) } } FUNC sayhelloName (http.ResponseWriter W, R & lt * http.Request){ r.ParseForm () fmt.Println("---------------") fmt.Println(r.Form) fmt.Println("path:", r.URL.Path) fmt.Println("scheme:", r.URL.Scheme) fmt.Println(r.Form["url_long"]) fmt.Println("====") for k, v := range r.Form{ fmt.Println("key:", k) fmt.Println("val:", strings.Join(v, " ")) } fmt.Fprintf(w, "Hello wang!") }
reference:
-
https://www.kancloud.cn/kancloud/the-way-to-go/165098 Go Getting Started Guide
-
http://wiki.jikexueyuan.com/project/go-web-programming/03.3.html Go Web Programming