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