书籍:The Way To Go,第五部分
Networking
A tcp server
import ( "fmt" "net" ) func main() { fmt.Println("Starting the server ...") listener, err := net.Listen("tcp", "localhost:50000") if err != nil { fmt.Println("Error listening", err.Error()) return // terminate program } for { conn, err := listener.Accept() if err != nil { fmt.Println("Error accepting", err.Error()) return } go doServerStuff(conn) } } func doServerStuff(conn net.Conn) { for { buf := make([]byte, 512) _, err := conn.Read(buf) if err != nil { fmt.Println("Error reading", err.Error()) return } fmt.Printf("Received data: %v", string(buf)) } }
func main() { conn, err := net.Dial("tcp", "localhost:50000") if err != nil { fmt.Println("Error dialing", err.Error()) return } inputReader := bufio.NewReader(os.Stdin) fmt.Println("First, what is your name?") clientName, _ := inputReader.ReadString('\n') // fmt.Printf("CLIENTNAME %s", clientName) trimmedClient := strings.Trim(clientName, "\r\n") for { fmt.Println("What to send to the server? Type Q to quit.") input, _ := inputReader.ReadString('\n') trimmedInput := strings.Trim(input, "\r\n") if trimmedInput == "Q" { return } _, err = conn.Write([]byte(trimmedClient + " says: " + trimmedInput)) } }
func main() { var ( host = "www.apache.org" port = "80" remote = host + ":" + port msg string = "GET / \n" data = make([]uint8, 4096) read = true count = 0 ) con, err := net.Dial("tcp", remote) io.WriteString(con, msg) for read { count, err = con.Read(data) read = (err == nil) fmt.Printf(string(data[0:count])) } con.Close() }
func initServer(hostAndPort string) *net.TCPListener { serverAddr, err := net.ResolveTCPAddr("tcp", hostAndPort) checkError(err, "Resolving address:port failed: '" + hostAndPort + "'") listener, err := net.ListenTCP("tcp", serverAddr) checkError(err, "ListenTCP: ") println("Listening to: ", listener.Addr().String()) return listener } func connectionHandler(conn net.Conn) { connFrom := conn.RemoteAddr().String() println(“Connection from: “, connFrom) sayHello(conn) for { var ibuf []byte = make([]byte, maxRead + 1) length, err := conn.Read(ibuf[0:maxRead]) ibuf[maxRead] = 0 // to prevent overflow switch err { case nil: handleMsg(length, err, ibuf) case os.EAGAIN: // try again continue default: goto DISCONNECT } } DISCONNECT: err := conn.Close() println("Closed connection: ", connFrom) checkError(err, "Close: ") }
a simple webserver
http.URL http.Request request.ParseForm(); var1, found := request.Form["var1"] http.Response http.StatusContinue = 100 http.StatusOK = 200 http.StatusFound = 302 http.StatusBadRequest = 400 |
resp, err := http.Head(url) resp.Status req.FormValue(“var1”) http.ResponseWriter http.StatusUnauthorized = 401 http.StatusForbidden = 403 http.StatusNotFound = 404 http.StatusInternalServerError=500 |
package main import ( "fmt" "net/http" "log" ) func HelloServer(w http.ResponseWriter, req *http.Request) { fmt.Println("Inside HelloServer handler") fmt.Fprint(w, "Hello," + req.URL.Path[1:]) // fmt.Fprintf(w, "<h1>%s</h1><div>%s</div>", title, body) } // w.Header().Set("Content-Type", "../..") func main() { http.HandleFunc(“/”,HelloServer) err := http.ListenAndServe(“localhost:8080”, nil) // http.ListenAndServe(“:8080”, http.HandlerFunc(HelloServer) // http.ListenAndServeTLS() if err != nil { log.Fatal("ListenAndServe: ", err.Error()) } }
func main() { xlsUrl := "http://market.finance.sina.com.cn/downxls.php?" xlsUrl += "date=2014-04-25&symbol=sz000002" res, err := http.Get(xlsUrl) CheckError(err) data, err := ioutil.ReadAll(res.Body) CheckError(err) fmt.Printf("%s", string(data)) } func CheckError(err error) { if err != nil { log.Fatalf("Get: %v", err) } }
// twitter_status.go type Status struct { Text string } type User struct { XMLName xml.Name Status Status } func main() { response, _ := http.Get("http://twitter.com/users/Googland.xml") user := User{xml.Name{"", "user"}, Status{""}} xml.Unmarshal(response.Body, &user) fmt.Printf("status: %s", user.Status.Text) }
// 附录 http.Redirect(w ResponseWriter, r *Request, url string, code int) http.NotFound(w ResponseWriter, r *Request) http.Error(w ResponseWriter, error string, code int)
// Making a web application robust type HandleFnc func(http.ResponseWriter,*http.Request) ... func main() { http.HandleFunc(“/test1”, logPanics(SimpleServer)) http.HandleFunc(“/test2”, logPanics(FormServer)) if err := http.ListenAndServe(“:8088”, nil); err != nil { panic(err) } } func logPanics(function HandleFnc) HandleFnc { return func(writer http.ResponseWriter, request *http.Request) { defer func() { if x := recover(); x != nil { log.Printf(“[%v] caught panic: %v”, request.RemoteAddr, x) } }() function(writer, request) } }
Sending mails with smtp
package main import ( “log” “smtp” ) func main() { auth := smtp.PlainAuth( “”, “user@example.com”, “password”, “mail.example.com”, ) err := smtp.SendMail( “mail.example.com:25”, auth, “sender@example.org”, []string{“recipient@example.net”}, []byte(“This is the email body.”), ) if err != nil { log.Fatal(err) } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。