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

月光独奏 · · 2335 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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)
     }
}



有疑问加站长微信联系(非本文作者)

本文来自:开源中国博客

感谢作者:月光独奏

查看原文:书籍:The Way To Go,第五部分

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2335 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传