Go語言伺服器開發實現最簡單HTTP的GET與POST介面_Golang

來源:互聯網
上載者:User

本文執行個體講述了Go語言伺服器開發實現最簡單HTTP的GET與POST介面。分享給大家供大家參考。具體分析如下:

Go語言提供了http包,可以很輕鬆的開發http介面。以下為範例程式碼:

複製代碼 代碼如下:
package webserver 
 
import ( 
    "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:" + password 
    fmt.Println(s) 
 
    if userName == "zhangsan" && password == "123456" { 
        result.Code = 100 
        result.Message = "登入成功" 
    } else { 
        result.Code = 101 
        result.Message = "使用者名稱或密碼不正確" 
    } 
 
        //向用戶端返回JSON資料 
    bytes, _ := json.Marshal(result) 
    fmt.Fprint(w, string(bytes)) 
}

NewBaseJsonBean用於建立一個struct對象:

複製代碼 代碼如下:
package webserver 
 
type BaseJsonBean struct { 
    Code    int         `json:"code"` 
    Data    interface{} `json:"data"` 
    Message string      `json:"message"` 

 
func NewBaseJsonBean() *BaseJsonBean { 
    return &BaseJsonBean{} 
}

希望本文所述對大家的Go語言程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.