feat: Move JSON decoder inside each hook.

This commit is contained in:
Nicolas Carlier 2014-09-25 12:19:51 +00:00
parent a2ebea6ba7
commit 0906ae1217
6 changed files with 55 additions and 5 deletions

View File

@ -1,7 +1,9 @@
package hook
import (
"encoding/json"
"fmt"
"net/http"
)
type BitbucketRecord struct {
@ -18,3 +20,23 @@ func (r BitbucketRecord) GetURL() string {
func (r BitbucketRecord) GetName() string {
return r.Repository.Slug
}
func (r BitbucketRecord) Decode(req *http.Request) error {
if err := req.ParseForm(); err != nil {
return err
}
if payload, ok := req.PostForm["payload"]; ok {
err := json.Unmarshal([]byte(payload[0]), &r)
if err != nil {
return err
}
} else {
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(&r)
if err != nil {
return err
}
}
return nil
}

View File

@ -1,5 +1,10 @@
package hook
import (
"encoding/json"
"net/http"
)
type DockerRecord struct {
Repository struct {
Name string `json:"repo_name"`
@ -14,3 +19,12 @@ func (r DockerRecord) GetURL() string {
func (r DockerRecord) GetName() string {
return r.Repository.Name
}
func (r DockerRecord) Decode(req *http.Request) error {
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(&r)
if err != nil {
return err
}
return nil
}

View File

@ -1,5 +1,10 @@
package hook
import (
"encoding/json"
"net/http"
)
type GithubRecord struct {
Repository struct {
Name string `json:"name"`
@ -14,3 +19,12 @@ func (r GithubRecord) GetURL() string {
func (r GithubRecord) GetName() string {
return r.Repository.Name
}
func (r GithubRecord) Decode(req *http.Request) error {
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(&r)
if err != nil {
return err
}
return nil
}

View File

@ -2,11 +2,13 @@ package hook
import (
"errors"
"net/http"
)
type Record interface {
GetURL() string
GetName() string
Decode(r *http.Request) error
}
func RecordFactory(hookname string) (Record, error) {

View File

@ -36,7 +36,7 @@ func NewHttpNotifier() *HttpNotifier {
}
func (n HttpNotifier) Notify(subject string, text string, attachfile string) {
log.Println("HTTP notification: ", subject)
log.Println("Sending notification '" + subject + "' to " + n.URL + " ...")
data := make(url.Values)
data.Set("from", n.From)
data.Set("to", n.To)
@ -88,7 +88,7 @@ func (n HttpNotifier) Notify(subject string, text string, attachfile string) {
log.Println("bad status: %s", res.Status)
return
}
log.Println("HTTP notification done with attachment: ", attachfile)
log.Println("HTTP notification sended with attachment: ", attachfile)
} else {
resp, err := http.PostForm(n.URL, data)
if err != nil {

View File

@ -1,7 +1,6 @@
package main
import (
"encoding/json"
"flag"
"fmt"
"github.com/gorilla/mux"
@ -105,8 +104,7 @@ func Handler(w http.ResponseWriter, r *http.Request) {
log.Println("Using hook: ", context.Hook)
decoder := json.NewDecoder(r.Body)
err = decoder.Decode(&record)
err = record.Decode(r)
if err != nil {
log.Println(err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)