~/Handling POST Requests in Golang
Mar 17, 2021
Use the net/http package to handle POST requests in Golang.
To accept and process POST requests, set up a handler function and read the request body. Always check the request method to ensure you handle only POST.
Example server code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
defer r.Body.Close()
fmt.Fprintf(w, "Received: %s", body)
}
func main() {
http.HandleFunc("/post", handler)
http.ListenAndServe(":8080", nil)
}
|
To test, use curl:
1
|
curl -X POST -d "sample=data" http://localhost:8080/post
|
For parsing JSON bodies, use encoding/json:
1
2
3
4
5
6
7
8
|
import "encoding/json"
type Payload struct {
Key string `json:"key"`
}
var p Payload
json.NewDecoder(r.Body).Decode(&p)
|
Always validate input properly to avoid security issues. Full details on HTTP servers in Go are in the Go HTTP Server docs.