github.com/go-playground/webhooks/v6@v6.3.0/azuredevops/azuredevops.go (about)

     1  package azuredevops
     2  
     3  // this package receives Azure DevOps Server webhooks
     4  // https://docs.microsoft.com/en-us/azure/devops/service-hooks/services/webhooks?view=azure-devops-2020
     5  
     6  import (
     7  	"encoding/json"
     8  	"errors"
     9  	"fmt"
    10  	"io"
    11  	"io/ioutil"
    12  	"net/http"
    13  )
    14  
    15  // parse errors
    16  var (
    17  	ErrInvalidHTTPMethod = errors.New("invalid HTTP Method")
    18  	ErrParsingPayload    = errors.New("error parsing payload")
    19  )
    20  
    21  // Event defines an Azure DevOps server hook event type
    22  type Event string
    23  
    24  // Azure DevOps Server hook types
    25  const (
    26  	BuildCompleteEventType         Event = "build.complete"
    27  	GitPullRequestCreatedEventType Event = "git.pullrequest.created"
    28  	GitPullRequestUpdatedEventType Event = "git.pullrequest.updated"
    29  	GitPullRequestMergedEventType  Event = "git.pullrequest.merged"
    30  	GitPushEventType               Event = "git.push"
    31  )
    32  
    33  // Webhook instance contains all methods needed to process events
    34  type Webhook struct {
    35  }
    36  
    37  // New creates and returns a WebHook instance
    38  func New() (*Webhook, error) {
    39  	hook := new(Webhook)
    40  	return hook, nil
    41  }
    42  
    43  // Parse verifies and parses the events specified and returns the payload object or an error
    44  func (hook Webhook) Parse(r *http.Request, events ...Event) (interface{}, error) {
    45  	defer func() {
    46  		_, _ = io.Copy(ioutil.Discard, r.Body)
    47  		_ = r.Body.Close()
    48  	}()
    49  
    50  	if r.Method != http.MethodPost {
    51  		return nil, ErrInvalidHTTPMethod
    52  	}
    53  
    54  	payload, err := ioutil.ReadAll(r.Body)
    55  	if err != nil || len(payload) == 0 {
    56  		return nil, ErrParsingPayload
    57  	}
    58  
    59  	var pl BasicEvent
    60  	err = json.Unmarshal([]byte(payload), &pl)
    61  	if err != nil {
    62  		return nil, ErrParsingPayload
    63  	}
    64  
    65  	switch pl.EventType {
    66  	case GitPushEventType:
    67  		var fpl GitPushEvent
    68  		err = json.Unmarshal([]byte(payload), &fpl)
    69  		return fpl, err
    70  	case GitPullRequestCreatedEventType, GitPullRequestMergedEventType, GitPullRequestUpdatedEventType:
    71  		var fpl GitPullRequestEvent
    72  		err = json.Unmarshal([]byte(payload), &fpl)
    73  		return fpl, err
    74  	case BuildCompleteEventType:
    75  		var fpl BuildCompleteEvent
    76  		err = json.Unmarshal([]byte(payload), &fpl)
    77  		return fpl, err
    78  	default:
    79  		return nil, fmt.Errorf("unknown event %s", pl.EventType)
    80  	}
    81  }