Skip to main content

Creating a Server

Basic POST Request Handler

To handle Webhook Notification messages, you would need a server that can handle POST requests since Webhook Notification will come as a POST request. To do that, this tutorial will provide all the necessities to create a server that handles POST request and understands the payload received from us.

This Golang example uses Golang Standard Library, if you’re unfamiliar with how Golang works, we recommend reading the official documentation here.

import (
"io"
"log"
"net/http"
)

func main() {
http.HandleFunc("/listener", func(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "Hello, world!")
})
log.Print("Server is running!")
log.Fatal(http.ListenAndServe(":8080", nil))
}

From the example above, We have successfully created a server to handle all the messages sent to the /listener path. We should try running it.

go run main.go

After running the command shown above you should see this message.

2020/06/30 19:02:29 Server is running!

Where the numbers on the left is the time our server prints the log.

And if you see the message like shown above, it means that your server is up and running. So then let’s continue to test it by running this command below.

curl -X POST 'http://localhost:8080/listener'

We should see a Hello, World! message.

Consuming JSON message

After successfully creating a web server to listen to Webhook Notification, you would have to understand the message received. Webhook Notification sends messages with JSON format. As for this example, we will guide you creating a Chat Notification payload which can be found here and then extract the field message and print it.

This Golang example uses Golang Standard Library, if you’re unfamiliar with how Golang works, we recommend reading the official documentation here.

import (
"io"
"log"
"net/http"
"encoding/json"
)

type ChatNotificationPayload struct {
MsgID int64 `json:"msg_id"`
BuyerID int64 `json:"buyer_id"`
Message string `json:"message"`
Thumbnail string `json:"thumbnail"`
FullName string `json:"full_name"`
ShopID int64 `json:"shop_id"`
}

func main() {
http.HandleFunc("/listener", func(w http.ResponseWriter, req *http.Request) {
var result ChatNotificationPayload
json.NewDecoder(req.Body).Decode(&result)
io.WriteString(w, result.Message)
})
log.Print("Server is running!")
log.Fatal(http.ListenAndServe(":8080", nil))
}

We can test the above code using this command below.

curl -X POST 'http://localhost:8080/listener' -d '{"message":"Hello, Tokopedia!"}'

After executing the command above, you should see Hello, Tokopedia!. And when you do, it means that you have successfully implemented a simple Webhook Notification Listener, Congratulations!.

Have a feedback?