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

POST / PUT

透過FORM(POST)方式送出資料到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形式資料

import "io/ioutil"
import "encoding/json"

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

搭配前端AngularJS 1.x $http 模擬FORM送出

$http({method:"post", "url": "...", headers: {"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"}, transformRequest: (data)=> {
   return $.param(data);
}
});

GET

  • 透過網址 http:www.justdrink.com.tw:8080/q=搜尋字串
package main

import(
   "net/http"
   "ion"
)

func main() {
   http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
      val := req.URL.Query().Get(q)
      io.WriteString(w, "Do you search:" + val)
   })
   http.ListenAndServe(":8080", nil)
}