golang server樣本

來源:互聯網
上載者:User

一個簡單的web伺服器

package mainimport (    "fmt"    "log"    "net/http")func main() {    http.HandleFunc("/", handler)    log.Fatal(http.ListenAndServe("localhost:8888", nil))}func handler(w http.ResponseWriter, r *http.Request) {    fmt.Println("url.path is ", r.URL.Path)}

簡單看下Request結構體中幾個重要成員

type Request struct {    // Form contains the parsed form data, including both the URL    // field's query parameters and the POST or PUT form data.    // This field is only available after ParseForm is called.    // The HTTP client ignores Form and uses Body instead.    Form url.Values    // PostForm contains the parsed form data from POST, PATCH,    // or PUT body parameters.    //    // This field is only available after ParseForm is called.    // The HTTP client ignores PostForm and uses Body instead.    PostForm url.Values    // MultipartForm is the parsed multipart form, including file uploads.    // This field is only available after ParseMultipartForm is called.    // The HTTP client ignores MultipartForm and uses Body instead.    MultipartForm *multipart.Form}

擷取get參數

func handler(w http.ResponseWriter, r *http.Request) {    r.ParseForm()    fmt.Println("value of param key is:", r.Form.Get("key"))}

擷取post參數

提交方式: application/x-www-form-urlencoded

func handler(w http.ResponseWriter, r *http.Request) {    r.ParseForm()    fmt.Println("value of param key is:", r.PostFormValue("key"))}

提交方式: json

type RequestParm struct {    Name      string `json:"name"`    Age       int    `json:"age"`    ScoreList []int  `json:"score_list"`}// NewDecoderfunc handler(w http.ResponseWriter, r *http.Request) {    req := &RequestParm{}    err := json.NewDecoder(r.Body).Decode(req)    if err != nil {        fmt.Println("json decode error")        return    }    fmt.Println(req)}// Unmarshalfunc handler(w http.ResponseWriter, r *http.Request) {    req := &RequestParm{}    body, err := ioutil.ReadAll(r.Body)    if err != nil {        panic(err)    }    err = json.Unmarshal(body, req)    if err != nil {        panic(err)    }    fmt.Println(req)}

參考資料

四種常見的 POST 提交資料方式

相關文章

聯繫我們

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