Go語言(伺服器開發):實現最簡單的HTTP GET/POST介面

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.