Go language (Server development): Implementing the simplest HTTP Get/post interface

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

The Go language provides an HTTP package that makes it easy to develop an HTTP interface. The following is the sample code:

Package Webserverimport ("Encoding/json" "FMT" "Net/http" "Time") func webserverbase () {fmt. Println ("This is webserver base!") The first parameter is the interface name when the client initiates an HTTP request, and the second parameter is a func that is responsible for processing the request. http. Handlefunc ("/login", Logintask)//server to listen on the host address and port number err: = http. Listenandserve ("192.168.1.27:8081", nil) if err! = Nil {fmt. PRINTLN ("Listenandserve error:", err.) Error ())}}func Logintask (w http. Responsewriter, req *http. Request) {fmt. Println ("Logintask is running ...")//analog delay time. Sleep (time. Second * 2)//Gets the parameters passed by the client through Get/post mode Req.parseform () param_username, Found1: = req. form["UserName"]param_password, Found2: = req. form["Password"]if! (Found1 && Found2) {FMT. Fprint (W, "Do not access illegally") Return}result: = Newbasejsonbean () UserName: = Param_username[0]password: = param_password[0]s: = " UserName: "+ userName +", Password: "+ passwordfmt. PRINTLN (s) if userName = = "Zhangsan" && password = = "123456" {result. Code = 100result. Message = "Login Succeeded"} else {result. Code = 101result. Message = "Username or password is incorrect"}       //to GuestThe client returns the JSON data bytes, _: = json. Marshal (Result) fmt. Fprint (w, string (bytes))}

Newbasejsonbean is used to create a struct object:

Package Webservertype basejsonbean struct {code    int         ' JSON: ' Code ' ' Data    interface{} ' JSON: ' Data ' ' Message ' String      ' JSON: ' message ' '}func Newbasejsonbean () *basejsonbean {return &basejsonbean{}}




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.