書籍:The Way To Go,第五部分

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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 mainimport (     "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.gotype 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 robusttype 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 mainimport (     “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)     }}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.