Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the post arguments in go server

Tags:

http

post

go

get

Below is an server written in go.

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
    fmt.Fprintf(w,"%s",r.Method)
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

How can I extract the POST data sent to the localhost:8080/something URL?

like image 347
footy Avatar asked May 12 '13 21:05

footy


2 Answers

Like this:

func handler(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()                     // Parses the request body
    x := r.Form.Get("parameter_name") // x will be "" if parameter is not set
    fmt.Println(x)
}
like image 54
thwd Avatar answered Oct 19 '22 08:10

thwd


Quoting from the documentation of http.Request

// 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
like image 7
zzzz Avatar answered Oct 19 '22 10:10

zzzz