github.com/predbdotovh/pre-api@v0.0.0-20211230223408-096f265fde6a/router.go (about)

     1  package main
     2  
     3  import (
     4  	"errors"
     5  	"log"
     6  	"net/http"
     7  
     8  	_ "github.com/go-sql-driver/mysql"
     9  	"github.com/gorilla/mux"
    10  )
    11  
    12  func newRouter(hostname string) *mux.Router {
    13  	backendUpdates = make(chan triggerAction)
    14  	go backendPump()
    15  
    16  	router := mux.NewRouter()
    17  
    18  	publicRouter := router.
    19  		StrictSlash(true).
    20  		Host(hostname).
    21  		PathPrefix("/api").
    22  		Subrouter()
    23  
    24  	for ver, jRoutes := range jsonRoutes {
    25  		versionRouter := publicRouter.PathPrefix("/" + ver).Subrouter()
    26  		for _, r := range jRoutes {
    27  			versionRouter.
    28  				Methods(r.Method).
    29  				Path(r.Pattern).
    30  				Name(r.Name).
    31  				Handler(httpLogger(r.Handler, r.Name))
    32  		}
    33  	}
    34  
    35  	privateRouter := router.
    36  		StrictSlash(true).
    37  		Host("localhost").
    38  		PathPrefix("/trigger").
    39  		Subrouter()
    40  
    41  	for _, r := range triggerRoutes {
    42  		privateRouter.
    43  			Methods(r.Method).
    44  			Path(r.Pattern).
    45  			Name(r.Name).
    46  			Handler(httpLogger(r.Handler, r.Name))
    47  	}
    48  
    49  	router.NotFoundHandler = http.HandlerFunc(notFound)
    50  
    51  	return router
    52  }
    53  
    54  func notFound(w http.ResponseWriter, _ *http.Request) {
    55  	w.Header().Set("Cache-Control", "no-store")
    56  	err := apiErr(w, errors.New("not Found"))
    57  	if err != nil {
    58  		log.Println(err)
    59  	}
    60  }