The Go language implements HTTP server and client

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

The use of the Go language Net/http package is very simple and elegant

(1) Service side

Package Mainimport ("Flag" "FMT" "Net/http") func main () {host: = flag. String ("Host", "127.0.0.1", "Listen Host") Port: = Flag. String ("Port", "Listen", "Port") http. Handlefunc ("/hello", hello) Err: = http. Listenandserve (*host+ ":" +*port, nil) if err! = Nil {panic (err)}}func Hello (w http. Responsewriter, req *http. Request) {<p>w.write ([]byte ("" Hello World ")] </p>}

http. Handlefunc is used to register a path handler function, which invokes different functions depending on the given path.

http. Listenandsercer Listen IP and port, native IP can omit not to write, only write colon plus port, such as HTTP. Listenandsercer (": 8080", nil)

The path handler function, the parameter must be W http. Responsewriter and req *http. Request and cannot have a return value

Test Result: Success


(2) Client

Package Mainimport ("FMT" "Io/ioutil" "Net/http") func main () {response, _: = http. Get ("Http://localhost:80/hello") defer response. Body.close () body, _: = Ioutil. ReadAll (response. Body) fmt. Println (String (body))}

Test Result: Success

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.