From d4c854ef814a980e825683cc2002d92458cc2cd1 Mon Sep 17 00:00:00 2001 From: wgroeneveld Date: Fri, 9 Apr 2021 21:00:54 +0200 Subject: [PATCH] implement gofmt and add a filewatcher in Goland --- .idea/watcherTasks.xml | 29 ++++++++++++++ app/index/handler.go | 12 +++--- app/logging.go | 27 +++++++------ app/mf/mention.go | 4 +- app/mf/microformats.go | 24 ++++++------ app/pingback/handler.go | 9 ++--- app/pingback/send/send.go | 2 +- app/pingback/send/send_test.go | 4 +- app/pingback/validate_test.go | 8 ++-- app/pingback/xmlrpc.go | 16 ++++---- app/pingback/xmlrpc_test.go | 2 +- app/routes.go | 2 - app/server.go | 37 +++++++++--------- app/server_test.go | 12 +++--- app/webmention/handler.go | 60 ++++++++++++++--------------- app/webmention/recv/receive.go | 35 ++++++++--------- app/webmention/recv/receive_test.go | 13 +++---- app/webmention/send/send.go | 2 +- app/webmention/validate.go | 1 - app/webmention/validate_test.go | 27 +++++++------ common/config.go | 29 +++++++------- common/slices_test.go | 4 +- main.go | 13 +++---- mocks/restclient.go | 11 +++--- playground.go | 14 +++---- rest/client.go | 8 ++-- rest/utils.go | 1 - rest/wrappers.go | 1 - 28 files changed, 208 insertions(+), 199 deletions(-) create mode 100644 .idea/watcherTasks.xml diff --git a/.idea/watcherTasks.xml b/.idea/watcherTasks.xml new file mode 100644 index 0000000..97ad6d2 --- /dev/null +++ b/.idea/watcherTasks.xml @@ -0,0 +1,29 @@ + + + + + + + + \ No newline at end of file diff --git a/app/index/handler.go b/app/index/handler.go index 9b9ed6e..9678324 100644 --- a/app/index/handler.go +++ b/app/index/handler.go @@ -1,17 +1,15 @@ - package index import ( - "net/http" "fmt" + "net/http" "brainbaking.com/go-jamming/common" ) func Handle(conf *common.Config) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, "This is a Jamstack microservice endpoint.\nWanna start jammin' too? Go to https://github.com/wgroeneveld/go-jamming !") - } + return func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + fmt.Fprintf(w, "This is a Jamstack microservice endpoint.\nWanna start jammin' too? Go to https://github.com/wgroeneveld/go-jamming !") + } } - diff --git a/app/logging.go b/app/logging.go index 6449173..85f0d55 100644 --- a/app/logging.go +++ b/app/logging.go @@ -1,4 +1,3 @@ - package app import ( @@ -8,24 +7,24 @@ import ( ) type loggingResponseWriter struct { - http.ResponseWriter - statusCode int + http.ResponseWriter + statusCode int } // mimic ResponseWriter's WriteHeader to capture the code func (lrw *loggingResponseWriter) WriteHeader(code int) { - lrw.statusCode = code - lrw.ResponseWriter.WriteHeader(code) + lrw.statusCode = code + lrw.ResponseWriter.WriteHeader(code) } func loggingMiddleware(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - logWriter := &loggingResponseWriter{w, http.StatusOK} - next.ServeHTTP(logWriter, r) - log.Info(). - Str("url", r.RequestURI). - Str("method", r.Method). - Int("status", logWriter.statusCode). - Msg("handled") - }) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + logWriter := &loggingResponseWriter{w, http.StatusOK} + next.ServeHTTP(logWriter, r) + log.Info(). + Str("url", r.RequestURI). + Str("method", r.Method). + Int("status", logWriter.statusCode). + Msg("handled") + }) } diff --git a/app/mf/mention.go b/app/mf/mention.go index a093029..6c91681 100644 --- a/app/mf/mention.go +++ b/app/mf/mention.go @@ -1,9 +1,9 @@ package mf import ( + "brainbaking.com/go-jamming/common" "crypto/md5" "fmt" - "brainbaking.com/go-jamming/common" "net/url" ) @@ -17,7 +17,7 @@ func (wm *Mention) String() string { } func (wm *Mention) AsPath(conf *common.Config) string { - filename := fmt.Sprintf("%x", md5.Sum([]byte("source=" + wm.Source+ ",target=" + wm.Target))) + filename := fmt.Sprintf("%x", md5.Sum([]byte("source="+wm.Source+",target="+wm.Target))) domain, _ := conf.FetchDomain(wm.Target) return conf.DataPath + "/" + domain + "/" + filename + ".json" } diff --git a/app/mf/microformats.go b/app/mf/microformats.go index 6cb9816..9042197 100644 --- a/app/mf/microformats.go +++ b/app/mf/microformats.go @@ -1,10 +1,10 @@ package mf import ( + "brainbaking.com/go-jamming/common" "strings" "time" "willnorris.com/go/microformats" - "brainbaking.com/go-jamming/common" ) const ( @@ -12,19 +12,19 @@ const ( ) type IndiewebAuthor struct { - Name string `json:"name"` - Picture string `json:"picture"` + Name string `json:"name"` + Picture string `json:"picture"` } type IndiewebData struct { - Author IndiewebAuthor `json:"author"` - Name string `json:"name"` - Content string `json:"content"` - Published string `json:"published"` - Url string `json:"url"` - IndiewebType string `json:"type"` - Source string `json:"source"` - Target string `json:"target"` + Author IndiewebAuthor `json:"author"` + Name string `json:"name"` + Content string `json:"content"` + Published string `json:"published"` + Url string `json:"url"` + IndiewebType string `json:"type"` + Source string `json:"source"` + Target string `json:"target"` } func PublishedNow(utcOffset int) string { @@ -134,4 +134,4 @@ func DetermineContent(hEntry *microformats.Microformat) string { } contentEntry := Map(hEntry, "content")["value"] return shorten(contentEntry) -} \ No newline at end of file +} diff --git a/app/pingback/handler.go b/app/pingback/handler.go index 765981f..a125888 100644 --- a/app/pingback/handler.go +++ b/app/pingback/handler.go @@ -1,19 +1,18 @@ - package pingback import ( - "encoding/xml" - "github.com/rs/zerolog/log" "brainbaking.com/go-jamming/app/mf" "brainbaking.com/go-jamming/app/webmention/recv" "brainbaking.com/go-jamming/common" "brainbaking.com/go-jamming/rest" + "encoding/xml" + "github.com/rs/zerolog/log" "io/ioutil" "net/http" ) func HandlePost(conf *common.Config) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { body, err := ioutil.ReadAll(r.Body) if err != nil { pingbackError(w, "Unable to read request body") @@ -94,5 +93,3 @@ func pingbackError(w http.ResponseWriter, msg string) { w.WriteHeader(200) w.Write([]byte(xml)) } - - diff --git a/app/pingback/send/send.go b/app/pingback/send/send.go index c457fbf..4e80682 100644 --- a/app/pingback/send/send.go +++ b/app/pingback/send/send.go @@ -1,9 +1,9 @@ package send import ( - "github.com/rs/zerolog/log" "brainbaking.com/go-jamming/app/mf" "brainbaking.com/go-jamming/rest" + "github.com/rs/zerolog/log" "strings" ) diff --git a/app/pingback/send/send_test.go b/app/pingback/send/send_test.go index 89f2a1d..260b18f 100644 --- a/app/pingback/send/send_test.go +++ b/app/pingback/send/send_test.go @@ -1,9 +1,9 @@ package send import ( - "github.com/stretchr/testify/assert" "brainbaking.com/go-jamming/app/mf" "brainbaking.com/go-jamming/mocks" + "github.com/stretchr/testify/assert" "testing" ) @@ -35,4 +35,4 @@ func TestSendPingbackToEndpoint(t *testing.T) { Target: "target", }) assert.Equal(t, expectedXml, capturedBody) -} \ No newline at end of file +} diff --git a/app/pingback/validate_test.go b/app/pingback/validate_test.go index 1ea977a..e5f9e68 100644 --- a/app/pingback/validate_test.go +++ b/app/pingback/validate_test.go @@ -1,9 +1,9 @@ package pingback import ( + "brainbaking.com/go-jamming/common" "encoding/xml" "github.com/stretchr/testify/assert" - "brainbaking.com/go-jamming/common" "testing" ) @@ -16,8 +16,8 @@ var conf *common.Config = &common.Config{ func TestValidate(t *testing.T) { cases := []struct { - label string - xml string + label string + xml string expected bool }{ { @@ -175,4 +175,4 @@ func TestValidate(t *testing.T) { assert.Equal(t, tc.expected, result) }) } -} \ No newline at end of file +} diff --git a/app/pingback/xmlrpc.go b/app/pingback/xmlrpc.go index 86be6e0..fe5b10b 100644 --- a/app/pingback/xmlrpc.go +++ b/app/pingback/xmlrpc.go @@ -15,11 +15,11 @@ import "encoding/xml" - */ +*/ type XmlRPCMethodCall struct { - XMLName xml.Name `xml:"methodCall"` - MethodName string `xml:"methodName"` - Params XmlRPCParams `xml:"params"` + XMLName xml.Name `xml:"methodCall"` + MethodName string `xml:"methodName"` + Params XmlRPCParams `xml:"params"` } func (rpc *XmlRPCMethodCall) Source() string { @@ -31,15 +31,15 @@ func (rpc *XmlRPCMethodCall) Target() string { } type XmlRPCParams struct { - XMLName xml.Name `xml:"params"` + XMLName xml.Name `xml:"params"` Parameters []XmlRPCParam `xml:"param"` } type XmlRPCParam struct { - XMLName xml.Name `xml:"param"` - Value XmlRPCValue `xml:"value"` + XMLName xml.Name `xml:"param"` + Value XmlRPCValue `xml:"value"` } type XmlRPCValue struct { String string `xml:"string"` -} \ No newline at end of file +} diff --git a/app/pingback/xmlrpc_test.go b/app/pingback/xmlrpc_test.go index f46b987..99ad99a 100644 --- a/app/pingback/xmlrpc_test.go +++ b/app/pingback/xmlrpc_test.go @@ -27,4 +27,4 @@ func TestMarshallValidXMLRPC(t *testing.T) { assert.Equal(t, "pingback.ping", rpc.MethodName) assert.Equal(t, "https://brainbaking.com/kristien.html", rpc.Params.Parameters[0].Value.String) assert.Equal(t, "https://kristienthoelen.be/2021/03/22/de-stadia-van-een-burn-out-in-welk-stadium-zit-jij/", rpc.Params.Parameters[1].Value.String) -} \ No newline at end of file +} diff --git a/app/routes.go b/app/routes.go index 220338a..3a78358 100644 --- a/app/routes.go +++ b/app/routes.go @@ -1,4 +1,3 @@ - package app import ( @@ -19,4 +18,3 @@ func (s *server) routes() { s.router.HandleFunc("/webmention/{domain}/{token}", s.authorizedOnly(webmention.HandleGet(cnf))).Methods("GET") s.router.HandleFunc("/webmention/{domain}/{token}", s.authorizedOnly(webmention.HandlePut(cnf))).Methods("PUT") } - diff --git a/app/server.go b/app/server.go index 1a9983a..e9b4cc5 100644 --- a/app/server.go +++ b/app/server.go @@ -1,4 +1,3 @@ - package app import ( @@ -13,33 +12,35 @@ import ( type server struct { router *mux.Router - conf *common.Config + conf *common.Config } // mimicing NotFound: https://golang.org/src/net/http/server.go?s=64787:64830#L2076 -func unauthorized(w http.ResponseWriter, r *http.Request) { http.Error(w, "401 unauthorized", http.StatusUnauthorized) } +func unauthorized(w http.ResponseWriter, r *http.Request) { + http.Error(w, "401 unauthorized", http.StatusUnauthorized) +} func (s *server) authorizedOnly(h http.HandlerFunc) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - if vars["token"] != s.conf.Token || !s.conf.IsAnAllowedDomain(vars["domain"]) { - unauthorized(w, r) - return - } + return func(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + if vars["token"] != s.conf.Token || !s.conf.IsAnAllowedDomain(vars["domain"]) { + unauthorized(w, r) + return + } h(w, r) } } func Start() { - r := mux.NewRouter() - config := common.Configure() - config.SetupDataDirs() - server := &server{router: r, conf: config} + r := mux.NewRouter() + config := common.Configure() + config.SetupDataDirs() + server := &server{router: r, conf: config} - server.routes() - http.Handle("/", r) - r.Use(loggingMiddleware) + server.routes() + http.Handle("/", r) + r.Use(loggingMiddleware) - log.Info().Int("port", server.conf.Port).Msg("Serving...") - http.ListenAndServe(":" + strconv.Itoa(server.conf.Port), nil) + log.Info().Int("port", server.conf.Port).Msg("Serving...") + http.ListenAndServe(":"+strconv.Itoa(server.conf.Port), nil) } diff --git a/app/server_test.go b/app/server_test.go index afb2c66..cb379d3 100644 --- a/app/server_test.go +++ b/app/server_test.go @@ -1,17 +1,17 @@ package app import ( + "brainbaking.com/go-jamming/common" "github.com/gorilla/mux" "github.com/stretchr/testify/assert" - "brainbaking.com/go-jamming/common" "net/http" "net/http/httptest" "testing" ) var conf = &common.Config{ - Token: "boemsjakkalakka", - AllowedWebmentionSources: []string{ "http://ewelja.be" }, + Token: "boemsjakkalakka", + AllowedWebmentionSources: []string{"http://ewelja.be"}, } func TestAuthorizedOnlyUnauthorizedWithWrongToken(t *testing.T) { @@ -26,7 +26,7 @@ func TestAuthorizedOnlyUnauthorizedWithWrongToken(t *testing.T) { r, _ := http.NewRequest("PUT", "/whatever", nil) w := httptest.NewRecorder() r = mux.SetURLVars(r, map[string]string{ - "token": "invalid", + "token": "invalid", "domain": conf.AllowedWebmentionSources[0], }) @@ -46,7 +46,7 @@ func TestAuthorizedOnlyUnauthorizedWithWrongDomain(t *testing.T) { r, _ := http.NewRequest("PUT", "/whatever", nil) w := httptest.NewRecorder() r = mux.SetURLVars(r, map[string]string{ - "token": conf.Token, + "token": conf.Token, "domain": "https://sexymoddafokkas.be", }) @@ -66,7 +66,7 @@ func TestAuthorizedOnlyOkIfTokenAndDomainMatch(t *testing.T) { r, _ := http.NewRequest("PUT", "/whatever", nil) w := httptest.NewRecorder() r = mux.SetURLVars(r, map[string]string{ - "token": conf.Token, + "token": conf.Token, "domain": conf.AllowedWebmentionSources[0], }) diff --git a/app/webmention/handler.go b/app/webmention/handler.go index 7a3d93e..36a0f44 100644 --- a/app/webmention/handler.go +++ b/app/webmention/handler.go @@ -1,12 +1,11 @@ - package webmention import ( - "fmt" - "github.com/gorilla/mux" "brainbaking.com/go-jamming/app/mf" "brainbaking.com/go-jamming/app/webmention/recv" "brainbaking.com/go-jamming/app/webmention/send" + "fmt" + "github.com/gorilla/mux" "net/http" "brainbaking.com/go-jamming/common" @@ -16,13 +15,13 @@ import ( var httpClient = &rest.HttpClient{} func HandleGet(conf *common.Config) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - fmt.Println("handling get") - } + return func(w http.ResponseWriter, r *http.Request) { + fmt.Println("handling get") + } } func HandlePut(conf *common.Config) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { since := getSinceQueryParam(r) domain := mux.Vars(r)["domain"] @@ -45,30 +44,29 @@ func getSinceQueryParam(r *http.Request) string { } func HandlePost(conf *common.Config) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - r.ParseForm() - if !validate(r, r.Header, conf) { - rest.BadRequest(w) - return - } - - target := r.FormValue("target") - if !isValidTargetUrl(target, httpClient) { - rest.BadRequest(w) - return - } + return func(w http.ResponseWriter, r *http.Request) { + r.ParseForm() + if !validate(r, r.Header, conf) { + rest.BadRequest(w) + return + } - wm := mf.Mention{ - Source: r.FormValue("source"), - Target: target, - } - recv := &recv.Receiver{ - RestClient: httpClient, - Conf: conf, - } + target := r.FormValue("target") + if !isValidTargetUrl(target, httpClient) { + rest.BadRequest(w) + return + } - go recv.Receive(wm) - rest.Accept(w) - } + wm := mf.Mention{ + Source: r.FormValue("source"), + Target: target, + } + recv := &recv.Receiver{ + RestClient: httpClient, + Conf: conf, + } + + go recv.Receive(wm) + rest.Accept(w) + } } - diff --git a/app/webmention/recv/receive.go b/app/webmention/recv/receive.go index 6b2914c..356b508 100644 --- a/app/webmention/recv/receive.go +++ b/app/webmention/recv/receive.go @@ -1,11 +1,10 @@ - package recv import ( - "encoding/json" "brainbaking.com/go-jamming/app/mf" "brainbaking.com/go-jamming/common" "brainbaking.com/go-jamming/rest" + "encoding/json" "io/fs" "io/ioutil" "os" @@ -16,9 +15,8 @@ import ( "willnorris.com/go/microformats" ) - -// used as a "class" to iject dependencies, just to be able to test. Do NOT like htis. -// Is there a better way? e.g. in validate, I just pass rest.Client as an arg. Not great either. +// used as a "class" to iject dependencies, just to be able to test. Do NOT like htis. +// Is there a better way? e.g. in validate, I just pass rest.Client as an arg. Not great either. type Receiver struct { RestClient rest.Client Conf *common.Config @@ -29,7 +27,7 @@ func (recv *Receiver) Receive(wm mf.Mention) { body, geterr := recv.RestClient.GetBody(wm.Source) if geterr != nil { - log.Warn().Str("source", wm.Source).Msg(" ABORT: invalid url") + log.Warn().Str("source", wm.Source).Msg(" ABORT: invalid url") recv.deletePossibleOlderWebmention(wm) return } @@ -50,7 +48,6 @@ func getHEntry(data *microformats.Data) *microformats.Microformat { return nil } - func (recv *Receiver) processSourceBody(body string, wm mf.Mention) { if !strings.Contains(body, wm.Target) { log.Warn().Str("target", wm.Target).Msg("ABORT: no mention of target found in html src of source!") @@ -92,14 +89,14 @@ func (recv *Receiver) parseBodyAsIndiewebSite(hEntry *microformats.Microformat, return &mf.IndiewebData{ Name: name, Author: mf.IndiewebAuthor{ - Name: mf.DetermineAuthorName(hEntry), + Name: mf.DetermineAuthorName(hEntry), Picture: pic, }, - Content: mf.DetermineContent(hEntry), - Url: mf.DetermineUrl(hEntry, wm.Source), - Published: mf.DeterminePublishedDate(hEntry, recv.Conf.UtcOffset), - Source: wm.Source, - Target: wm.Target, + Content: mf.DetermineContent(hEntry), + Url: mf.DetermineUrl(hEntry, wm.Source), + Published: mf.DeterminePublishedDate(hEntry, recv.Conf.UtcOffset), + Source: wm.Source, + Target: wm.Target, IndiewebType: mfType, } } @@ -115,12 +112,12 @@ func (recv *Receiver) parseBodyAsNonIndiewebSite(body string, wm mf.Mention) *mf Author: mf.IndiewebAuthor{ Name: wm.Source, }, - Name: title, - Content: title, - Published: mf.PublishedNow(recv.Conf.UtcOffset), - Url: wm.Source, + Name: title, + Content: title, + Published: mf.PublishedNow(recv.Conf.UtcOffset), + Url: wm.Source, IndiewebType: "mention", - Source: wm.Source, - Target: wm.Target, + Source: wm.Source, + Target: wm.Target, } } diff --git a/app/webmention/recv/receive_test.go b/app/webmention/recv/receive_test.go index d30e4b3..aa2e338 100644 --- a/app/webmention/recv/receive_test.go +++ b/app/webmention/recv/receive_test.go @@ -1,10 +1,9 @@ - package recv import ( + "brainbaking.com/go-jamming/app/mf" "errors" "github.com/stretchr/testify/assert" - "brainbaking.com/go-jamming/app/mf" "io/ioutil" "os" "testing" @@ -15,13 +14,12 @@ import ( ) var conf = &common.Config{ - AllowedWebmentionSources: []string { + AllowedWebmentionSources: []string{ "jefklakscodex.com", }, DataPath: "testdata", } - func TestConvertWebmentionToPath(t *testing.T) { wm := mf.Mention{ Source: "https://brainbaking.com", @@ -37,7 +35,7 @@ func TestConvertWebmentionToPath(t *testing.T) { func writeSomethingTo(filename string) { file, _ := os.Create(filename) file.WriteString("lolz") - defer file.Close() + defer file.Close() } func TestReceive(t *testing.T) { @@ -45,7 +43,7 @@ func TestReceive(t *testing.T) { label string wm mf.Mention json string - } { + }{ { label: "receive a Webmention bookmark via twitter", wm: mf.Mention{ @@ -137,7 +135,7 @@ func TestReceiveTargetDoesNotExistAnymoreDeletesPossiblyOlderWebmention(t *testi GetBodyFunc: func(url string) (string, error) { return "", errors.New("whoops") }, - } + } receiver := &Receiver{ Conf: conf, RestClient: client, @@ -181,4 +179,3 @@ func TestProcessSourceBodyAbortsIfNoMentionOfTargetFoundInSourceHtml(t *testing. receiver.processSourceBody("my nice body", wm) assert.NoFileExists(t, wm.AsPath(conf)) } - diff --git a/app/webmention/send/send.go b/app/webmention/send/send.go index c383c73..6254c31 100644 --- a/app/webmention/send/send.go +++ b/app/webmention/send/send.go @@ -1,11 +1,11 @@ package send import ( - "github.com/rs/zerolog/log" "brainbaking.com/go-jamming/app/mf" "brainbaking.com/go-jamming/app/pingback/send" "brainbaking.com/go-jamming/common" "brainbaking.com/go-jamming/rest" + "github.com/rs/zerolog/log" ) type Sender struct { diff --git a/app/webmention/validate.go b/app/webmention/validate.go index 63be91c..62798fd 100644 --- a/app/webmention/validate.go +++ b/app/webmention/validate.go @@ -1,4 +1,3 @@ - package webmention import ( diff --git a/app/webmention/validate_test.go b/app/webmention/validate_test.go index 6f4bd5b..e88a3bc 100644 --- a/app/webmention/validate_test.go +++ b/app/webmention/validate_test.go @@ -1,10 +1,9 @@ - package webmention import ( - "testing" "errors" "net/http" + "testing" "brainbaking.com/go-jamming/common" "brainbaking.com/go-jamming/mocks" @@ -17,14 +16,18 @@ type httpReqMock struct { type httpHeaderMock struct { contentType string } + func (mock *httpHeaderMock) Get(key string) string { return mock.contentType } func (mock *httpReqMock) FormValue(key string) string { switch key { - case "source": return mock.source - case "target": return mock.target - default: return "" + case "source": + return mock.source + case "target": + return mock.target + default: + return "" } } func buildHttpReq(source string, target string) *httpReqMock { @@ -38,12 +41,12 @@ var config = common.Configure() func TestValidate(t *testing.T) { cases := []struct { - label string - source string - target string + label string + source string + target string contentType string - expected bool - } { + expected bool + }{ { "is valid if source and target https urls", "http://brainbaking.com/bla1", @@ -105,14 +108,14 @@ func TestValidate(t *testing.T) { for _, tc := range cases { t.Run(tc.label, func(t *testing.T) { httpReq := buildHttpReq(tc.source, tc.target) - httpHeader := &httpHeaderMock{ contentType: tc.contentType } + httpHeader := &httpHeaderMock{contentType: tc.contentType} actual := validate(httpReq, httpHeader, config) if actual != tc.expected { t.Fatalf("got %v, want %v", actual, tc.expected) } }) - } + } } func TestIsValidTargetUrlFalseIfGetFails(t *testing.T) { diff --git a/common/config.go b/common/config.go index 5aaacb5..cd1fd61 100644 --- a/common/config.go +++ b/common/config.go @@ -1,4 +1,3 @@ - package common import ( @@ -11,11 +10,11 @@ import ( ) type Config struct { - Port int - Token string - UtcOffset int - DataPath string - AllowedWebmentionSources []string + Port int + Token string + UtcOffset int + DataPath string + AllowedWebmentionSources []string DisallowedWebmentionDomains []string } @@ -39,15 +38,15 @@ func (c *Config) FetchDomain(url string) (string, error) { func (c *Config) SetupDataDirs() { for _, domain := range c.AllowedWebmentionSources { - os.MkdirAll(c.DataPath + "/" + domain, os.ModePerm) + os.MkdirAll(c.DataPath+"/"+domain, os.ModePerm) log.Info().Str("allowedDomain", domain).Msg("Configured") } } func Configure() (c *Config) { portstr := os.Getenv("PORT") - port, err := strconv.Atoi(portstr) - if err != nil { + port, err := strconv.Atoi(portstr) + if err != nil { port = 1337 } token := os.Getenv("TOKEN") @@ -56,12 +55,12 @@ func Configure() (c *Config) { } c = &Config{ - Port: port, - Token: token, - UtcOffset: 60, - DataPath: "data", - AllowedWebmentionSources: []string{ "brainbaking.com", "jefklakscodex.com" }, - DisallowedWebmentionDomains: []string{ "youtube.com" }, + Port: port, + Token: token, + UtcOffset: 60, + DataPath: "data", + AllowedWebmentionSources: []string{"brainbaking.com", "jefklakscodex.com"}, + DisallowedWebmentionDomains: []string{"youtube.com"}, } return } diff --git a/common/slices_test.go b/common/slices_test.go index 07c2a31..ad0abc5 100644 --- a/common/slices_test.go +++ b/common/slices_test.go @@ -3,7 +3,7 @@ package common import "testing" func TestIncludesElemInArrayTrue(t *testing.T) { - arr := []string{ "one", "two"} + arr := []string{"one", "two"} result := Includes(arr, "two") if result != true { @@ -12,7 +12,7 @@ func TestIncludesElemInArrayTrue(t *testing.T) { } func TestIncludesElemNotInArrayFalse(t *testing.T) { - arr := []string{ "one", "two"} + arr := []string{"one", "two"} result := Includes(arr, "three") if result != false { diff --git a/main.go b/main.go index 5bfbbc8..ecb4499 100644 --- a/main.go +++ b/main.go @@ -1,4 +1,3 @@ - package main import ( @@ -6,15 +5,15 @@ import ( "brainbaking.com/go-jamming/app" - "github.com/rs/zerolog" - "github.com/rs/zerolog/log" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" ) func main() { - zerolog.TimeFieldFormat = zerolog.TimeFormatUnix - // TODO this should only be enabled in local mode. Fix with config? - log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) + zerolog.TimeFieldFormat = zerolog.TimeFormatUnix + // TODO this should only be enabled in local mode. Fix with config? + log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) - log.Debug().Msg("Let's a go!") + log.Debug().Msg("Let's a go!") app.Start() } diff --git a/mocks/restclient.go b/mocks/restclient.go index e7159d0..b877724 100644 --- a/mocks/restclient.go +++ b/mocks/restclient.go @@ -1,21 +1,20 @@ - package mocks import ( - "strings" - "testing" "io/ioutil" "net/http" + "strings" + "testing" ) // neat trick! https://medium.com/@matryer/meet-moq-easily-mock-interfaces-in-go-476444187d10 type RestClientMock struct { - GetFunc func(string) (*http.Response, error) + GetFunc func(string) (*http.Response, error) GetBodyFunc func(string) (string, error) - PostFunc func(string, string, string) error + PostFunc func(string, string, string) error } -// although these are still requied to match the rest.Client interface. +// although these are still requied to match the rest.Client interface. func (m *RestClientMock) Get(url string) (*http.Response, error) { return m.GetFunc(url) } diff --git a/playground.go b/playground.go index 8660ab2..1c74b44 100644 --- a/playground.go +++ b/playground.go @@ -2,9 +2,9 @@ package main import ( "fmt" - "log" - "net/http" "io/ioutil" + "log" + "net/http" ) func mainz() { @@ -14,11 +14,11 @@ func mainz() { log.Fatalln(err) } - body, err2 := ioutil.ReadAll(resp.Body) - if err2 != nil { - log.Fatalln(err) - } + body, err2 := ioutil.ReadAll(resp.Body) + if err2 != nil { + log.Fatalln(err) + } - fmt.Printf("tis ditte") + fmt.Printf("tis ditte") fmt.Printf("%s", body) } diff --git a/rest/client.go b/rest/client.go index e7a9a09..a2703d3 100644 --- a/rest/client.go +++ b/rest/client.go @@ -1,4 +1,3 @@ - package rest import ( @@ -32,9 +31,9 @@ func (client *HttpClient) GetBody(url string) (string, error) { return "", geterr } - if resp.StatusCode < 200 || resp.StatusCode > 299 { - return "", fmt.Errorf("Status code for %s is not OK (%d)", url, resp.StatusCode) - } + if resp.StatusCode < 200 || resp.StatusCode > 299 { + return "", fmt.Errorf("Status code for %s is not OK (%d)", url, resp.StatusCode) + } defer resp.Body.Close() body, readerr := ioutil.ReadAll(resp.Body) @@ -45,7 +44,6 @@ func (client *HttpClient) GetBody(url string) (string, error) { return string(body), nil } - func (client *HttpClient) Get(url string) (*http.Response, error) { return http.Get(url) } diff --git a/rest/utils.go b/rest/utils.go index 065ce44..e24336b 100644 --- a/rest/utils.go +++ b/rest/utils.go @@ -1,4 +1,3 @@ - package rest import ( diff --git a/rest/wrappers.go b/rest/wrappers.go index a3f9387..e77f80c 100644 --- a/rest/wrappers.go +++ b/rest/wrappers.go @@ -1,4 +1,3 @@ - package rest // great, these are needed to do the structural typing for the tests...