Created
July 28, 2017 03:06
-
-
Save moehandi/90f6b19b4e9e871d68e0c7627214aadd to your computer and use it in GitHub Desktop.
Go API versioning
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net/http" | |
"github.com/gorilla/mux" | |
) | |
// AnotherHandlerLatest is the newest version of AnotherHandler | |
func AnotherHandlerLatest(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, "hello from AnotherHandlerLatest.") | |
} | |
// ExampleHandlerLatest is the newest version of ExampleHandler | |
func ExampleHandlerLatest(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, "hello from ExampleHandlerLatest.") | |
} | |
// ExampleHandlerV1 is a v1-compatible version of ExampleHandler | |
func ExampleHandlerV1(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, "Hello from ExampleHandlerv1.") | |
} | |
// AddV1Routes takes a router or subrouter and adds all the v1 | |
// routes to it | |
func AddV1Routes(r *mux.Router) { | |
r.HandleFunc("/example", ExampleHandlerV1) | |
AddRoutes(r) | |
} | |
// AddV2Routes takes a router or subrouter and adds all the v2 | |
// routes to it, note that these should probably match | |
// AddRoutes(r *muxRouter) alternatively you can do | |
// var AddV2Routes = AddRoutes | |
func AddV2Routes(r *mux.Router) { | |
AddRoutes(r) | |
} | |
// AddRoutes takes a router or subrouter and adds all the latest | |
// routes to it | |
func AddRoutes(r *mux.Router) { | |
r.HandleFunc("/example", ExampleHandlerLatest) | |
r.HandleFunc("/example2", AnotherHandlerLatest) | |
} | |
func main() { | |
router := mux.NewRouter() | |
// latest | |
AddRoutes(router) | |
// v1 | |
AddV1Routes(router.PathPrefix("/v1").Subrouter()) | |
// v2 | |
AddV2Routes(router.PathPrefix("/v2").Subrouter()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment