This article describes the Go language server development to achieve the simplest HTTP GET and post interface. Share to everyone for your reference. The specific analysis is as follows:
The Go language provides an HTTP package that makes it easy to develop HTTP interfaces. The following is sample code:
Copy Code code as follows:
Package webserver
Import (
"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 handles the request.
http. Handlefunc ("/login", Logintask)
Host address and port number to be monitored by the server
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 that the client passes by Get/post
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:" + password
Fmt. PRINTLN (s)
if userName = = "Zhangsan" && password = = "123456" {
Result. Code = 100
Result. Message = "Login Succeeded"
} else {
Result. Code = 101
Result. Message = "Incorrect user name or password"
}
Return JSON data to the client
Bytes, _: = json. Marshal (Result)
Fmt. Fprint (w, string (bytes))
}
Newbasejsonbean is used to create a struct object:
Copy Code code as follows:
Package webserver
Type Basejsonbean struct {
Code int ' JSON: ' Code '
Data interface{} ' JSON: ' Data '
Message string ' JSON: ' message '
}
Func Newbasejsonbean () *basejsonbean {
Return &basejsonbean{}
}
I hope this article will help you with your go language program.