Book: The Go, part fifth

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

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   &nbSp;       }          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&NBsp;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 =  "          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,  " 
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)                                                       &nBsp;    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)} 
//  Appendix 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 {      &Nbsp;         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)      }}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.