3. Centralized URL path definition Before, we had to redefine the URL path in multiple tiers of the app. In the API client, our code is like this RESP, err: = http. Get (FMT. Sprintf ("%s/api/repos/%s", C.baseurl, name)) This is an easy way to throw an error because we have more than 75 path definitions, and many are complex. A centralized URL path definition means that the path is refactored from the API server in a new package. The path definition is declared in the path package. Const Repogetroute = "Repo" func newapirouter () *mux. Router {m: = Mux. Newrouter ()//define the Routes M.path ("/api/repos/{name:.*}"). Name (Repogetroute) return m}while the HTTP. Handlers were actually mounted in the API server Package:func init () {m: = Newapirouter ()//Mount handlers m.ge T (Repogetroute). Handlerfunc (handlerepoget) http. Handle ("/api/", M)} and HTTP. Handlers is actually mounted in the API server package: Func init () {m: = Newapirouter ()//Mount handlers M.get (Repogetroute). Handlerfunc (handlerepoget) http. Handle ("/api/", M)} Now we can use the path package to generate URLs in the API client instead of writing them to death. (*reposervice). The Get method is now as follows: var apirouter = Newapirouter () func (S *reposervice) Get (name string) (*repo, error) {URL, _: = Apirouter.get (Repogetro Ute). URL ("name", name) resp, err: = http. Get (S.baseurl + URL. String ()) if err! = Nil {return nil, err} defer resp. Body.close () var repo []repo return repo, json. Newdecoder (resp. Body). Decode (&repo)}
|