這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
Go語言提供了http包,可以很輕鬆的開發http介面。以下為範例程式碼:
package webserverimport ("encoding/json""fmt""net/http""time")func WebServerBase() {fmt.Println("This is webserver base!")//第一個參數為用戶端發起http請求時的介面名,第二個參數是一個func,負責處理這個請求。http.HandleFunc("/login", loginTask)//伺服器要監聽的主機地址和連接埠號碼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...")//類比延時time.Sleep(time.Second * 2)//擷取用戶端通過GET/POST方式傳遞的參數req.ParseForm()param_userName, found1 := req.Form["userName"]param_password, found2 := req.Form["password"]if !(found1 && found2) {fmt.Fprint(w, "請勿非法訪問")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 = "登入成功"} else {result.Code = 101result.Message = "使用者名稱或密碼不正確"} //向用戶端返回JSON資料bytes, _ := json.Marshal(result)fmt.Fprint(w, string(bytes))}
NewBaseJsonBean用於建立一個struct對象:
package webservertype BaseJsonBean struct {Code int `json:"code"`Data interface{} `json:"data"`Message string `json:"message"`}func NewBaseJsonBean() *BaseJsonBean {return &BaseJsonBean{}}