Skip to content

Commit

Permalink
chore: replace gorilla/mux by http.ServerMux (#349)
Browse files Browse the repository at this point in the history
  • Loading branch information
linxside authored Feb 24, 2024
1 parent 618c0a6 commit 2903490
Show file tree
Hide file tree
Showing 8 changed files with 220 additions and 141 deletions.
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ go 1.22

require (
github.com/google/uuid v1.6.0
github.com/gorilla/mux v1.8.1
github.com/miekg/dns v1.1.58
github.com/mvmaasakkers/certificates v0.7.2
github.com/nats-io/nats.go v1.33.1
Expand Down
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/klauspost/compress v1.17.2 h1:RlWWUY/Dr4fL8qk9YG7DTZ7PDgME2V4csBXA8L/ixi4=
Expand Down
14 changes: 11 additions & 3 deletions internal/app/pdns-api-proxy/internalserviceproxy/httphandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func defaultProxy(respond http.ResponseWriter, incomingrequest *http.Request) {
logger.ErrorErrLog(preparerequesterr)
}

httputils.CopyHTTPHeader(incomingrequest.Header, proxyrequest.Header)
proxyrequest.Header = incomingrequest.Header.Clone()

proxyresponse, proxyexecuteerr := proxyclient.Do(proxyrequest) //nolint:bodyclose
if proxyexecuteerr != nil {
Expand All @@ -114,14 +114,22 @@ func defaultProxy(respond http.ResponseWriter, incomingrequest *http.Request) {
return
}

defer httputils.CloseResponseBody(proxyresponse)
defer func(Body io.ReadCloser) {
if err := Body.Close(); err != nil {
logger.ErrorErrLog(err)
}
}(proxyresponse.Body)

proxyresponsebody, proxyresponsereaderr := io.ReadAll(proxyresponse.Body)
if proxyresponsereaderr != nil {
logger.ErrorErrLog(proxyresponsereaderr)
}

httputils.CopyHTTPHeader(proxyresponse.Header, respond.Header())
for key, values := range proxyresponse.Header {
for _, value := range values {
respond.Header().Add(key, value)
}
}

respond.WriteHeader(proxyresponse.StatusCode)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"net/http"
"time"

"github.com/gorilla/mux"
"github.com/nameserver-systems/pdns-distribute/internal/app/pdns-api-proxy/certificate"
"github.com/nameserver-systems/pdns-distribute/internal/app/pdns-api-proxy/config"
"github.com/nameserver-systems/pdns-distribute/internal/pkg/httputils"
Expand Down Expand Up @@ -45,7 +44,8 @@ func startHTTPServer(serviceconfig *config.ServiceConfiguration) error {

const serverwritetimeout = 15 * time.Second

router := getNewRouterWithRoutes()
router := http.NewServeMux()
registerRoutes(router)

serviceurl := serviceconfig.ServiceURL

Expand Down Expand Up @@ -79,16 +79,3 @@ func startHTTPServer(serviceconfig *config.ServiceConfiguration) error {

return nil
}

func getNewRouterWithRoutes() *mux.Router {
router := getNewRouter()
router.StrictSlash(true)

registerRoutes(router)

return router
}

func getNewRouter() *mux.Router {
return mux.NewRouter()
}
29 changes: 14 additions & 15 deletions internal/app/pdns-api-proxy/internalserviceproxy/routes.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,24 @@
//nolint:lll
package internalserviceproxy

import (
"github.com/gorilla/mux"
"net/http"
)

func registerRoutes(router *mux.Router) {
router.HandleFunc("/api/v1/servers/{server_id}/zones", createZoneHandler(defaultProxy)).Methods("POST")
router.HandleFunc("/api/v1/servers/{server_id}/zones/{zone_id}/rectify", changeZoneHandler(defaultProxy)).Methods("PUT")
router.HandleFunc("/api/v1/servers/{server_id}/zones/{zone_id}", changeZoneHandler(defaultProxy)).Methods("PUT")
router.HandleFunc("/api/v1/servers/{server_id}/zones/{zone_id}", changeZoneHandler(defaultProxy)).Methods("PATCH")
router.HandleFunc("/api/v1/servers/{server_id}/zones/{zone_id}", deleteZoneHandler(defaultProxy)).Methods("DELETE")
func registerRoutes(router *http.ServeMux) {
router.HandleFunc("POST /api/v1/servers/{server_id}/zones", createZoneHandler(defaultProxy))
router.HandleFunc("PUT /api/v1/servers/{server_id}/zones/{zone_id}/rectify", changeZoneHandler(defaultProxy))
router.HandleFunc("PUT /api/v1/servers/{server_id}/zones/{zone_id}", changeZoneHandler(defaultProxy))
router.HandleFunc("PATCH /api/v1/servers/{server_id}/zones/{zone_id}", changeZoneHandler(defaultProxy))
router.HandleFunc("DELETE /api/v1/servers/{server_id}/zones/{zone_id}", deleteZoneHandler(defaultProxy))

router.HandleFunc("/api/v1/servers/{server_id}/zones/{zone_id}/metadata", changeZoneHandler(defaultProxy)).Methods("POST")
router.HandleFunc("/api/v1/servers/{server_id}/zones/{zone_id}/metadata/{metadata_kind}", changeZoneHandler(defaultProxy)).Methods("PUT")
router.HandleFunc("/api/v1/servers/{server_id}/zones/{zone_id}/metadata/{metadata_kind}", changeZoneHandler(defaultProxy)).Methods("DELETE")
router.HandleFunc("POST /api/v1/servers/{server_id}/zones/{zone_id}/metadata", changeZoneHandler(defaultProxy))
router.HandleFunc("PUT /api/v1/servers/{server_id}/zones/{zone_id}/metadata/{metadata_kind}", changeZoneHandler(defaultProxy))
router.HandleFunc("DELETE /api/v1/servers/{server_id}/zones/{zone_id}/metadata/{metadata_kind}", changeZoneHandler(defaultProxy))

router.HandleFunc("/api/v1/servers/{server_id}/zones/{zone_id}/cryptokeys", changeZoneHandler(defaultProxy)).Methods("POST")
router.HandleFunc("POST /api/v1/servers/{server_id}/zones/{zone_id}/cryptokeys", changeZoneHandler(defaultProxy))

router.HandleFunc("/api/v1/servers/{server_id}/zones/{zone_id}/cryptokeys/{cryptokey_id}", changeZoneHandler(defaultProxy)).Methods("PUT")
router.HandleFunc("/api/v1/servers/{server_id}/zones/{zone_id}/cryptokeys/{cryptokey_id}", changeZoneHandler(defaultProxy)).Methods("DELETE")
router.HandleFunc("PUT /api/v1/servers/{server_id}/zones/{zone_id}/cryptokeys/{cryptokey_id}", changeZoneHandler(defaultProxy))
router.HandleFunc("DELETE /api/v1/servers/{server_id}/zones/{zone_id}/cryptokeys/{cryptokey_id}", changeZoneHandler(defaultProxy))

router.PathPrefix("/").HandlerFunc(defaultProxy)
router.HandleFunc("/", defaultProxy)
}
74 changes: 20 additions & 54 deletions internal/pkg/httputils/httputils.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,89 +8,62 @@ import (
"net/http"
neturl "net/url"
"strconv"
"strings"

"github.com/gorilla/mux"
"github.com/miekg/dns"
"github.com/nameserver-systems/pdns-distribute/pkg/microservice/logger"
)

func CopyHTTPHeader(src, dest http.Header) {
for key, values := range src {
for _, value := range values {
dest.Add(key, value)
}
}
}

func GetZoneIDFromRequest(r *http.Request) (string, error) {
var err error

zoneid := getZoneIDFromRequestPath(r)

if hasNotFoundZoneID(zoneid) {
zoneid, err = getZoneIDFromRequestBody(r, zoneid)
if len(zoneid) == 0 {
zoneid, err = getZoneIDFromRequestBody(r)
if err != nil {
return "", err
}
}

zoneid = ensureTrailingDot(zoneid)
zoneid = dns.Fqdn(zoneid)

return zoneid, nil
}

func ensureTrailingDot(zoneid string) string {
if !strings.HasSuffix(zoneid, ".") {
zoneid += "."
}

return zoneid
}

func getZoneIDFromRequestBody(r *http.Request, zoneid string) (string, error) {
func getZoneIDFromRequestBody(r *http.Request) (zoneID string, err error) {
var result map[string]interface{}

incomingbodybytes, readerr := io.ReadAll(r.Body)
if readerr != nil {
return "", readerr
incomingbodybytes, err := io.ReadAll(r.Body)
if err != nil {
return
}

closerr := r.Body.Close()
if closerr != nil {
return "", closerr
if err = r.Body.Close(); err != nil {
return
}

// necessary due to io.ReadAll clears after read the body and body is used for proxy
r.Body = io.NopCloser(bytes.NewBuffer(incomingbodybytes))

unmarshalerr := json.Unmarshal(incomingbodybytes, &result)
if unmarshalerr != nil {
return "", unmarshalerr
if err = json.Unmarshal(incomingbodybytes, &result); err != nil {
return
}

if rawzoneid, okid := result["id"]; okid {
zoneid = rawzoneid.(string)
zoneID = rawzoneid.(string)
} else if rawzonename, okname := result["name"]; okname {
zoneid = rawzonename.(string)
zoneID = rawzonename.(string)
}

if hasNotFoundZoneID(zoneid) {
return "", errZoneIDNotFound
if len(zoneID) == 0 {
err = errZoneIDNotFound
}

return zoneid, nil
return
}

func getZoneIDFromRequestPath(r *http.Request) string {
vars := mux.Vars(r)

zoneid := vars["zone_id"]

return zoneid
}

func hasNotFoundZoneID(zoneid string) bool {
return zoneid == ""
return r.PathValue("zone_id")
}

func GetHostAndPortFromURL(url string) (string, error) {
Expand Down Expand Up @@ -121,13 +94,6 @@ func GetHostnameFromURL(url string) (string, error) {
return hostname, parseerr
}

func CloseResponseBody(response *http.Response) {
err := response.Body.Close()
if err != nil {
logger.ErrorErrLog(err)
}
}

func ExecutePowerDNSRequest(method, url, apitoken string, body io.Reader) (string, error) {
var client http.Client

Expand All @@ -143,14 +109,14 @@ func ExecutePowerDNSRequest(method, url, apitoken string, body io.Reader) (strin
return "", executeerr
}

defer CloseResponseBody(response)
defer response.Body.Close()

responsebody, responsereaderr := io.ReadAll(response.Body)
if responsereaderr != nil {
return "", responsereaderr
}

if 200 > response.StatusCode || response.StatusCode >= 300 {
if !IsStatusCodeSuccesful(response.StatusCode) {
logger.ErrorLog("invalid pdns answer with http status" + strconv.Itoa(response.StatusCode) + " with message: " + string(responsebody))

return "", errInvalidPDNSAPIAnswer
Expand Down
Loading

0 comments on commit 2903490

Please sign in to comment.