An API framework for GO

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. # Goweb A tool based on the go Language Development API, this tool is inspired by SPRINGMVC, combining the features of the go language itself, the overall is relatively simple, next, see how to use it. Download install: ' Go get github.com/alberliu/goweb ' # # # 1. Core function # # # Request body Parameter injection ' ' Gopackage mainimport "Github.com/alberliu/goweb" Type user struct {id int ' JSON: ' id ' ' name string ' JSON: ' name ' '}func handler (user user) user {return User}func main () {Goweb . Handlepost ("/test", Handler) Goweb. Listenandserve (": 8000")} ' request body: ' json{' id ': 1, ' name ': ' Alber '} ' ' response body: ' json{' id ': 1, ' name ': ' Alber '} ' The above code is a minimalist example, Handlepost (string, interface{}) registers a handler with a global built-in Goweb instance Defultgoweb,listenandserve (": 8000") Assigns the Defultgoweb to the server's handler variable, and then starts the server. (not a bit like the built-in servermux) goweb automatically resolves the handler registered to itself, and when the request arrives, the JSON data of the request body is deserialized and injected into the handler parameters, and when the logical return is processed, The return value of the handler is serialized as a JSON data return. Goweb uses JSON serialization and deserialization by default, and of course you can define your own serialization method, which you can see later. The parameters and returns of the handler given in the example are struct types, and of course you can use the pointer type. Structure Goweb is essentially a route, it implements the handler interface. The above example is the default Defultgoweb, you can also instantiate a goweb yourself. "' Gofunc Main () {Goweb:=goweb. Newgoweb (); Goweb. Handlepost ("/test", HandlER) Server: = &http. SERVER{ADDR: "8000", Handler:goweb}server. Listenandserve ()} "" # # # # # URL parameter injection ' gopackage mainimport ' github.com/alberliu/goweb ' type User struct {Id int64 ' JSON: ' ID "' Name string ' JSON:" name "'}func handler (ID int64, name string) User {return user{id, Name}}func main () {goweb: = Goweb. Newgoweb (); Goweb. Handleget ("/test/{id}/{name}", Handler) Goweb. Listenandserve (": 8000")} "executes the above code and then accesses Url:http://localhost:8000/test/123456/alber to return to the following JSON data" "json{" id ": 123456, "name": "Alber"} "handler can get the parameters in the URL and inject into the handler parameter. The first parameter of the handler corresponds to the first parameter in the URL, the second parameter corresponds to the second parameter in the URL, and so on. However, there is a temporary limitation, when using parameters in a URL, the parameters in handler must match the number of parameters in the URL, and the type must be string or int64. # # # 2.handlergoweb can register many forms of Handler,goweb will use reflection to automatically parse functions, supporting multiple types, but not beyond the scope it can parse. Here are all the types that it can parse. "' Gofunc handler (CTX Goweb. Context) {}func handler (CTX Goweb. Context) User {return User{}}func handler (user user) user {return User{}}func handler (CTX Goweb. Context, user user) user {return User{}}func handler (name string, id Int64) user {return user{}}Func handler (CTX Goweb. Context, name string, id Int64) User {return user{}} ' is a request context, he has only responsewriter and request two fields, and its internal structure is as follows. You can modify the source according to your own needs to expand, for example, to use it as a requested session. "' Gotype Context struct {w http. Responsewriterr *http. Request} ' # # 3. Organize your handler ' Gofunc main () {Group1:=goweb with group. NewGroup ("/group1") group1. Handleget ("/handler1", Handler) group1. Handleget ("/handler2", Handler) group1. Handleget ("/handler3", Handler) Group2:=goweb. NewGroup ("/group2") group2. Handleget ("/handler1", Handler) group2. Handleget ("/handler2", Handler) group2. Handleget ("/handler3", Handler) Group3:=goweb. NewGroup ("/group3") group3. Handleget ("/handler1", Handler) Group3. Handleget ("/handler2", Handler) Group3. Handleget ("/handler3", Handler) Goweb. Handlegroup (group1) goweb. Handlegroup (group2) goweb. Handlegroup (GROUP3) goweb. Listenandserve (": 8000")} ' group can help you organize your handler hierarchically, making your routing structure clearer. # # # 4. Define your own serialization and deserialization session mode ' ' ' govar json = Jsoniter. Configcompatiblewithstandardlibraryfunc Jsonunmarshal (data []byte, v interface{}) error {return JSON. Unmarshal (data, V)}func Jsonmarshal (v interface{}) ([]byte, error) {return JSON. Marshal (v)}func main () {Goweb:=goweb. Newgoweb (); Goweb. Unmarshal=jsonunmarshalgoweb.marshal=jsonmarshalgoweb.listenandserve (": 8000")} "goweb default to JSON (using open source Jsoniter Serializing and deserializing data, Goweb's marshal, unmarshal variable itself is a function. If you want to define your own serialization, you just need to overwrite it, just like above. # # # 5. Interceptor ' Gofunc Interceptor1 (http. Responsewriter, *http. Request) bool {return True}func Interceptor2 (http. Responsewriter, *http. Request) bool {return True}func Interceptor3 (http. Responsewriter, *http. Request) BOOL {return True}func main () {goweb: = Goweb. Newgoweb (); Goweb. Addinterceptor (Interceptor1) goweb. Addinterceptor (Interceptor2) goweb. Addinterceptor (Interceptor3) goweb. Listenandserve (": 8000")} ' Goweb executes one or more interceptor before executing the handler, and is executed according to the Addinterceptor order, When Interceptor returns true, execution goes down, and when false returns, it is terminated. # # # 6. Filter "" Gofunc Filter (w http. Responsewriter, R *http. Request, F func (http. Responsewriter, *http. Request) {f (W, R)}func main () {goweb: = Goweb. Newgoweb (); Goweb. FiLter = Filtergoweb. Listenandserve (": 8000")} "you can add a goweb to the filter, and if you want to execute the handler after you have executed your logic, just call F (W, R). # # # 7. Custom error Handling "' Gofunc handler400 (w http. Responsewriter, R *http. Request) {W.writeheader (W.write) ([]byte ("Bad Request")}func handler404 (w http). Responsewriter, R *http. Request) {W.writeheader (404) W.write ([]byte ("url not Found"))}func handler405 (w http. Responsewriter, R *http. Request) {W.writeheader (405) W.write ([]byte ("Method not Found"))}func main () {goweb: = Goweb. Newgoweb () goweb.handler400 = handler400goweb.handler404 = handler404goweb.handler405 = Handler405goweb. Listenandserve (": 8000")} "when a request execution fails, some default error handling is given in Goweb, as above. Of course, you can also define some of your own error handling methods. # # # Write in the back if you have any good suggestions, you can send me the mailbox, communicate with each other. alber_liu@qq.com1199 Times Click  

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.