I am building a simple router for which the code is below.
type Res http.ResponseWriter
type Res http.ResponseWritertype Res response.Response
I looked at the http.ResponseWriter source code and noticed it is an interface whereas my response.Response is a struct, is this where the problem lies?
Does setting a type as another type does not necessarily alias it? And if not, then why did passing in http.ResponseWriter for type Res work initially?
package Router
import (
"fmt"
"net/http"
"net/url"
"log"
// "./response"
)
// type Res response.Response
type Res http.ResponseWriter
type Req *http.Request
type RouteMap map[string]func(Res, Req)
type MethodMap map[string]RouteMap
type Router struct {
Methods MethodMap
}
func (router *Router) Get(urlString string, callback func(Res, Req)) {
parsedUrl, err := url.Parse(urlString)
if(err != nil) {
panic(err)
}
router.Methods["GET"][parsedUrl.Path] = callback
}
func (router *Router) initMaps() {
router.Methods = MethodMap{}
router.Methods["GET"] = RouteMap{}
}
func (router Router) determineHandler(w http.ResponseWriter, r *http.Request) {
methodMap := router.Methods[r.Method]
urlCallback := methodMap[r.URL.Path]
// newResponse := response.NewResponse(w)
if(urlCallback != nil) {
// urlCallback(newResponse, r)
urlCallback(w, r)
}
}
func (router Router) Serve(host string, port string) {
fullHost := host + ":" + port
fmt.Println("Router is now serving to:" + fullHost)
http.HandleFunc("/", router.determineHandler)
err := http.ListenAndServe(fullHost, nil)
if err == nil {
fmt.Println("Router is now serving to:" + fullHost)
} else {
fmt.Println("An error occurred")
log.Fatal(err)
}
}
The commented out code describes the issue im having/what im trying to do