Use Go to write a service container (services Container)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. I've been working on a fairly large API project recently, including many routing rules (routes), service Interfaces (services), and processing functions (handlers). First, I noticed that the startup process of the ' main.go ' file started getting bloated. To avoid setting up a global service interface, I use a shared fabric body (struct) to bind the service interface to the handler function. For example: Main.go ' gopackage mainfunc main () {r: = gin. Default () Userrepo: = models. Newuserrepo (drives. DataStore (). C ("Users"), Userhandler: = handlers. Newuserhandler (Userrepo) r.get ("/api/v1/users", Userhandler.findall) R.run (": 8080")} ' User_handler.go ' Gotype Userhandler struct {Userrepo *models. Userrepo}func Newuserhandler (Userrepo *models. Userrepo) *userhandler {return &userhandler{Userrepo,}}func (Userhandler *userhandler) FindAll (c *gin. Context) {users, err: = UserHandler.userRepo.FindAll () if err! = nil {C.json (404, Nil) return} c.json (users) retur n} "The code works fine, but you'll find that in main.go, I'm just writing a few boot-up processes that just contain a handler function and a persisted data (repository). Writing code in this way is cumbersome and bloated. So I want to write a container with Go. I can't find a third-party library I like to solve this problem. So, come up with the following code. ' Goimport ("sync") type Container struct{mux sync. Rwmutex m map[string]interface{}}// Add Servicefunc (c *container) Add (name string, Object interface{}) {C.mux.lock () if c.m = nil {c.m = make (map[string] interface{})} C.m[name] = Object C.mux.unlock ()}//remove Servicefunc (c *container) remove (name string) Container {c.mu X.lock () Delete (C.M, name) C.mux.unlock ()}//get a Servicefunc (c *container) get (name string) (Object interface{}, BOOL) {C.mux.rlock () object, OK = C.m[name] C.mux.runlock () return object, OK} "note that each method of this code uses ' mutex lock ' to avoid container concurrency problems. Now the code can write ... "' Gofunc GetContainer () Container {c: = new (Container. Container) C.add ("User.handler", handlers. Userhandler) return C} ' now Main.go ' gofunc main () {container: = container. GetContainer () Userhandler, OK: = container. Get ("User.handler") if!ok {log. Fatal ("Service Not Found")} r.get ("/api/v1/users", Userhandler. ( *handlers. Userhandler). FindAll (),)} ' _ Sync code reference from Itsmontoya, salute to him _ now I've encapsulated the boot process very succinctly into a package. I think a person with a PHP background will refer to the [pimple] (http://pimple.sensiolabs.org/) framework when considering this syntax implementation. I have abstracted this into my own library, implemented in [here] (hTtps://github.com/ewanvalentine/vertebrae).

via:https://ewanvalentine.io/writing-a-service-container-in-go/

Author: Ewan Valentine Translator: jzhongming proofreading: Rxcai

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

1864 Reads
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.