Golang WebHook using chi router

Issue

I am creating a service in Go with chi router and I need to implement a WebHook for one of my endpoints. I am using this library to create my webHook. However I am having problems when I try to receive it and decode it. In their sample code they used Gin framework and I have to use chi. My receivedSignature comes out as nil and I get an error: interface conversion: interface {} is nil, not string .

Could anyone please help me with a work around on this?

Here is my send function:

    data := []int{1, 2, 3, 4}
    // String sent in the GoHook that helps identify actions to take with data
    resource := "int-list-example"
    // Secret string that should be common to sender and receiver
    // in order to validate the GoHook signature
    saltSecret := "0014716e-392c-4120-609e-555e295faff5"

    hook := &gohooks.GoHook{}
    hook.Create(data, resource, saltSecret)

    // Will return *http.Response and error
    resp, err := hook.Send("http://localhost:3001/")
    if err != nil {
        fmt.Println("error: ", err)
    }
    fmt.Println("resp: ", resp)

And here is my receiving logic:

func main(){
    r := chi.NewRouter()
    r.Use(middleware.Logger)
    r.Post("/", receiveWebHook)
    http.ListenAndServe(":3001", r)
}

type MyWebhook struct {
    Resource string `json:"resource"`
    Data []int `json:"data"`
}

func receiveWebHook(w http.ResponseWriter, r *http.Request){
    var request MyWebhook
    err := json.NewDecoder(r.Body).Decode(&request)
    if err !=nil{
        fmt.Println("err: ", err)
    }
    // Shared secret with sender
    saltSecret := "0014716e-392c-4120-609e-555e295faff5"

    receivedSignature := r.Context().Value(gohooks.DefaultSignatureHeader).(string)
    // Verify validity of GoHook
    isValid := gohooks.IsGoHookValid(request, receivedSignature, saltSecret)
    // Decide what to do if GoHook is valid or not.
    if !isValid {
        fmt.Println("Not valid, receivedSignature: ", receivedSignature)
    }else{
        fmt.Println("Valid, receivedSignature: ", receivedSignature)
    }
    w.WriteHeader(200)
}

Solution

The signature will be in a header. So you should also read it from the requests’ header.

sig := r.Header.Get(gohooks.DefaultSignatureHeader)

Answered By – The Fool

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.