Network of Golang

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

Network of Golang

The Go Language standard library provides NET packages that support network operations based on the IP layer, TCP/UDP layer, and higher (such as HTTP, FTP, SMTP), which are used for the IP layer called raw sockets.

NET package dial () function is used to create a network connection, the function prototype is as follows:

Func Dial (NET, addr string) (Conn, error)

The net parameter is the name of the network protocol, the addr parameter is the IP address or domain name, and if the connection succeeds, the connection object is returned, otherwise error is returned.

Currently, the Dial () function supports the following network protocols: "TCP", "UDP", "IP", "IP6", etc., such as:

Conn, Err: = Net. Dial ("TCP", "192.168.0.10:2100")// TCP connection conn, err:= net. Dial ("UDP", "192.168.0.12:975")  // UDP Connection conn, err:= net. Dial ("ip4:icmp", "www.baidu.com")//ICMP connection

After the connection is successfully connected, you can use the write () and read () methods of Conn to read and write data.

In fact, the Dial () function is the encapsulation of the DIALTCP (), DIALUDP (), Dialip (), and Dialunix () functions:

Func dialtcp (NET string, laddr, Raddr *tcpaddr) (c **udpaddr) (c * *ipaddr) (c * *unixaddr) (c *u Nixconn, err Error)

The following is a sample TCP program:

func checkerror (err error) {ifErr! =Nil {fmt. fprintf (OS. Stderr,"Fatal Error:%s", Err. Error ()) OS. Exit (1)}}func readfully (conn net. Conn) ([]byte, error) {Defer Conn. Close () Result:=bytes. Newbuffer (Nil) var buf [512]bytefor {n, err:= Conn. Read (buf[0:]) Result. Write (buf[0: n])ifErr! =Nil {ifErr = =io. EOF {break} return nil, err}} return result. Bytes (), nil}func main () {addr:= "127.0.0.1:80"Conn, err:= Net. Dial ("TCP", addr) checkerror (Err) _, Err= Conn. Write ([]byte("Get/api/v3/get http/1.1\r\n\r\n") CheckError (Err) result, err:=readfully (conn) checkerror (err) fmt. PRINTLN (string result) os. Exit (0)}

HTTP protocol

The Go Language standard library provides a net/http package that covers the specific implementations of the HTTP client and server.

HTTP Client

The client type of the Net/http package provides the following methods:

Func (c *client) Get (URL string) (R **client) Post (URL string, bodyType string, body io. Reader) (R **client) postform (URL string, data URL.) Values) (R **client) Head (URL string) (R **client) do (req *request) (r *response, err error)

Take the Get method as an example:

RESP, err: = http. Get ("Http://cre.mix.sina.com.cn/api/v3/get")

If err! = Nil {
Fmt. Println ("Get Failed", err)
Return
}

Defer resp. Body.close ()

Io. Copy (OS. Stdout, resp. Body)

The above code requests a site home page and prints its contents to the standard output stream.

If you want more control over the request, you can use the Do () method:

Req, Err: = http. Newrequest ("GET", "Http://cre.mix.sina.com.cn/api/v3/get", nil) req. Header.add ("user-agent", "Go Go") client:= &http. CLIENT{}RESP, err:= client. Do (req)

HTTP Service Side

The following two methods are available using the Net/http package

Func listenandserve (addr string, handler handler) Errorfunc Listenandservetls (addr string, certfile string, KeyFile Strin G, handler handler) error

The Listenandserve () function has 2 parameters, the first parameter addr is the listener address, and the second parameter represents the service-side handler, usually empty, using the default HTTP. Defaultservemux for processing.

The service-side business logic uses HTTP. Handle () or HTTP. Handlefunc (), HTTP is injected by default. Defaultservemux, such as:

http. Handlefunc ("/foo", func (w http). Responsewriter, R *http. Request) {        "Hello,%q", HTML. Escapestring (R.url. Path)    }) http. Listenandserve (": 8001", nil)

RPC protocol

In go, the NET/RPC package provided by the standard library implements the relevant details required by the PRC protocol, and developers can easily use the package to write RPC server and client programs.

JSON processing

In the field of web development, JSON is widely used for data communication between Web service-side programs and clients.

The go language is built to support JSON, and with the Encoding/json standard library, developers can easily use the Go program to generate and parse data in JSON format.

Func Marshal (v interface{}) ([]byte, Error) func unmarshal (vdata []byte, v interface{}) error

An example of JSON encoding:

type book struct {Title string Authors [] string Publisher string ispublished bool Price Float32}func Main () {gobook:=Book {"Go Programming", []string {"Xushiwei", "Hughlv", "Johnson"},        "Isturing.com.cn",        true,        9.99,    }           //encode B, err:=JSON. Marshal (Gobook)//variable B is a []byte typeifErr = =Nil {fmt. Println (b)}//decode var book book JSON. Unmarshal (b,&Book ) fmt. Println (book)}

When we call JSON. The Marshal (Gobook) function recursively iterates through the Gobook object if it finds that the Gobook data structure implements JSON. Marshaler the interface and contains a valid value, Marshal () calls its Marshaljson () method to generate JSON-formatted text for the data structure.

Most types of the go language can be converted to valid JSON text, except for the channel, complex, and function types, while for pointers it translates to the value pointed to by the pointer, and if the pointer is to a value of 0, then NULL will be the result of the converted output. The specific conversion rules are as follows:

    • Boolean value converted to JSON type bool;
    • Floating-point and integer conversions to the number type of JSON;
    • The string converts the string to a Unicode character set in UTF-8 encoding;
    • Arrays and slices are converted to JSON array types, but values of []byte types are converted to BASE64 encoded strings, and 0 values of slice types are converted to null;
    • The struct is converted to a JSON object type, and only the exportable fields that begin with an uppercase letter in the struct are converted to output;
    • When converting a data structure of a map type, the data must be of type map[string] T.

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.