GO API: Router
In this post, we will define router for our GOLANG API project.
For now, copy below code and paste it in router.go file
In this post, we will define router for our GOLANG API project.
For now, copy below code and paste it in router.go file
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.package app import ( "github.com/gorilla/mux" . "test.com/goapi/app/apis" "net/http" "fmt" ) type Route struct { Name string Method string Pattern string HandlerFunc http.HandlerFunc } type Routes []Route func NewRouter() *mux.Router { router := mux.NewRouter().StrictSlash(true) for _, route := range routes { var handler http.Handler handler = route.HandlerFunc router. Methods(route.Method). Path(route.Pattern). Name(route.Name). Handler(handler) } return router } func Index(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World") } var routes = Routes{ Route{ "Index", "GET", "/v1/", Index, }, Route{ "GetAllStudent", "GET", "/v1/student", GetAllStudentInfo, }, Route{ "GetStudent", "GET", "/v1/student/{student-id}", GetStudentInfo, }, Route{ "PostStudent", "POST", "/v1/student", CreateStudentInfo, }, Route{ "UpdateStudent", "PATCH", "/v1/student/{student-id}", UpdateStudentInfo, }, Route{ "DeleteStudent", "DELETE", "/v1/student/{student-id}", DeleteStudentInfo, }, }
Comments
Post a Comment