取得GET、POST到Server的資料(FORM、JSON)

透過FORM方式送出資料到Server

func chkLoginFromWeb(w http.ResponseWriter, r *http.Request) {
   if err := r.ParseForm(); err != nil {
      fmt.Fprintf(w, "%v", err)
      return
   }
   var user UserCredentials
   user.Username = r.FormValue("username")
   user.Password = r.FormValue("password")
   if user.Username == "" || user.Password == "" {
      w.WriteHeader(http.StatusForbidden)
      fmt.Fprintf(w, "Wrong Username or Password.")
      return
   }

   if strings.ToLower(user.Username) != "andyliu" || strings.ToLower(user.Password) != "pass@word" {
      w.WriteHeader(http.StatusForbidden)
      fmt.Fprintf(w, "Error in request.")
      return
   }

   response, err := user.CreateJWT(SecretKey)
   if err != nil {
      w.WriteHeader(http.StatusForbidden)
      fmt.Fprintf(w, "Error while signing the token.")
      return
   }
   JsonResponse(response, w)
}

透過JSON形式送資料到Server

import "io/ioutil"

func chkLoginFromJSON(w http.ResponseWriter, r *http.Request) {
   if err := r.ParseForm(); err != nil {
      fmt.Fprintf(w, "%v", err)
      return
   }
   b, err := ioutil.ReadAll(r.Body)
   defer r.Body.Close()
   if err != nil {
      fmt.Fprintf(w, "Error in parse request body.%v", err)
      return
   }
   var user UserCredentials
   if err := json.Unmarshal(b, &user); err != nil {
      w.WriteHeader(http.StatusForbidden)
      fmt.Fprintf(w, "%v", b)
      fmt.Fprintf(w, "Error in Ummarshal request body.%v", err)
      return
   }
   response, err := user.CreateJWT(SecretKey)
   if err != nil {
      w.WriteHeader(http.StatusForbidden)
      fmt.Fprintf(w, "Error while signing the token.")
      return
   }
   JsonResponse(response, w)
}