[Go] golang http下返回json數據


需求返回json格式編碼的結構體 , 需要返回content-type 

返回不同的響應碼

 

結構體的定義 ,因為可導出的結構體 ,必須大寫,如果要小寫 ,就得加這個別名

type JsonResult  struct{
    Code int `json:"code"`
    Msg  string `json:"msg"`
}

從post中獲取到字段后 , 返回對應的結果 , 設置header必須在返回響應碼之前調用

//驗證接口
func check(w http.ResponseWriter, r *http.Request) {
    email := r.PostFormValue("email")
    server := r.PostFormValue("server")
    password := r.PostFormValue("password")
    msg, _ := json.Marshal(tools.JsonResult{Code: 400, Msg: "驗證失敗"})

    w.Header().Set("content-type","text/json")
    if email != "" && server != "" && password != "" {
        res := tools.CheckEmailPassword(server, email, password)
        if res {
            msg, _ = json.Marshal(tools.JsonResult{Code: 200, Msg: "驗證成功"})
            w.Write(msg)
        } else {
            w.WriteHeader(400)
            w.Write(msg)
        }
    } else {
        w.WriteHeader(400)
        w.Write(msg)
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM