package main
import (
"fmt"
"log"
"net/http"
"strings"
)
func main() {
// the forward slash at the end is important for path parameters:
http.HandleFunc("/testendpoint/", testendpoint)
err := http.ListenAndServe(":8888", nil)
if err != nil {
log.Println("ListenAndServe: ", err)
}
}
func testendpoint(w http.ResponseWriter, r *http.Request) {
// If you want a good line of code to get both query or form parameters
// you can do the following:
param1 := r.FormValue("param1")
fmt.Fprintf( w, "Parameter1: %s ", param1)
//to get a path parameter using the standard library simply
param2 := strings.Split(r.URL.Path, "/")
// make sure you handle the lack of path parameters
if len(param2) > 4 {
fmt.Fprintf( w, " Parameter2: %s", param2[5])
}
}
You can run the code in aapi playground here
Add this to your access url: /mypathparameeter?param1=myqueryparam
I wanted to leave the link above for now, because it gives you a nice place to run the code, and I believe its helpful to be able to see it in action, but let me explain some typical situations where you might want a post argument.
There are a few typical ways developers will pull post data to a back end server, usually multipart form data will be used when pulling files from the request, or large amounts of data, so I don't see how thats relevant here, at least in the context of the question. He is looking for post arguments which typically means form post data. Usually form post arguments are sent in a web form to the back end server.
When a user is submitting a login form or registration data back to golang from html, the Content Type header coming from the client in this case would be application/x-www-form-urlencoded typically, which I believe is what the question is asking, these would be form post arguments, which are extracted with r.FormValue("param1").
In the case of grabbing json from the post body, you would grab the entire post body and unmarshal the raw json into a struct, or use a library to parse the data after you have pulled the data from the request body, Content Type header application/json.
Content Type header is largely responsible for how you will parse the data coming from the client, I have given an example of 2 different content types, but there are many more.