您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關golang如何實現一個restful微服務的操作,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
golang 是Google開發的一種靜態強類型、編譯型、并發型,并具有垃圾回收功能的編程語言,其語法與 C語言相近,但并不包括如枚舉、異常處理、繼承、泛型、斷言、虛函數等功能。
Golang提供了簡潔的方法來構建web服務
package main import ( "net/http" ) func HelloResponse(rw http.ResponseWriter, request *http.Request) { fmt.Fprintf(w, "Hello world.") } func main() { http.HandleFunc("/", HelloResponse) http.ListenAndServe(":3000", nil) }
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)):HandleFunc注冊一個handler function對應到給定的pattern。
func ListenAndServe(addr string, handler Handler) error:ListenAndServe監聽給定的TCP網絡地址,接著帶上handler調用Serve方法來接收請求。
在go build之后,執行編譯后的文件就能在客戶端看到hello world了
我認為作為第一版本,不需要復雜的設計,只需要接收到用戶的請求,并且找到對應的handler,執行其邏輯,然后返回JSON響應就好了。
據我觀察,一些框架是在Controller里預先設定了GET,POST,PUT等一系列方法,負責接收GET,POST,PUT的HTTP請求。
我認為這樣設計的確有其優勢,因為用戶只需要實現這些方法就好了,但在業務層面也有其劣勢,因為我們沒有辦法保證負責一個頁面或者功能的Controller只接收一個GET請求,如果有2個GET請求,那就需要再建立一個Controller,單單實現其GET方法。
因此我借鑒了PHP社區中Laravel注冊Controller和Action的語法:Get("/", "IndexController@Index")。
用戶只需要定義:
type IndexController struct { } func (IndexController *IndexController) Index(//params) (//return values) { }
當然這樣思考后,就給框架帶入了一點動態腳本語言的特性,肯定會用到Golang的reflect庫。
我運用了Golang的map,定義了map[string]map[string]map[string]string這樣的數據結構
以["/":["GET":["IndexController":"Get"], "POST":["IndexController":"Post"]], "/foo":["GET":["IndexController":"Foo"]]]舉例:
這個說明了在"/"這個PATH下面,有GET和POST請求,分別對應了IndexController下的Get和Post方法,在"/foo"這個PATH下面,有GET請求,對應IndexController下的Foo方法。
在接受請求時候,如果沒有找到對應的方法,就返回405。
我們可以看到,func HandleFunc(pattern string, handler func(ResponseWriter, *Request))要求的handler類型是func(ResponseWriter, *Request)),這和我們設計的functionfunc (IndexController *IndexController) Index(//params) (//return values) {}有所差距。
這時候我發現由于Golang具備First Class Functions特性,因此我們可以將函數做如下處理:
http.HandleFunc(path, HandleRequest()) func HandleRequest() { return func(rw http.ResponseWriter, request *http.Request) { // do your logic } }
當我們接收到function的返回值后,我們就需要對結果進行json encode,而encoding/json正是負責這個功能。 我用的是json.Marshal():
func Marshal(v interface{}) ([]byte, error): Marshal返回v的encoding結果。
package main import ( "net/url" "net/http" "github.com/ZhenhangTung/GoGym" ) type IndexController struct { } func (IndexController *IndexController) Index(request map[string]url.Values, headers http.Header) (statusCode int, response interface{}) { return 200, map[string]string{"hello": "world"} } type BarController struct { } func (*BarController) Bar(request map[string]url.Values, headers http.Header) (statusCode int, response interface{}, responseHeader http.Header) { return 200, map[string]string{"GoTo": "Bar"}, http.Header{"Foo": {"Bar", "Baz"}} } func main() { var apiService = GoGym.Prepare() apiService.Get("index", "IndexController@Index") apiService.Post("bar", "BarController@Bar") controllers := []interface{}{&IndexController{}} apiService.RegisterControllers(controllers) apiService.RegisterController(&BarController{}) apiService.Serve(3000) }
package GoGym import ( "encoding/json" "fmt" "net/http" "net/url" "reflect" "strings" ) const ( GETMethod = "GET" POSTMethod = "POST" PUTMethod = "PUT" PATCHMethod = "PATCH" DELETEMethod = "DELETE" OPTIONSMethod = "OPTIONS" ) const ( HTTPMethodNotAllowed = 405 ) // APIService for now is the struct for containing controllerRegistry and registeredPathAndController, // and it is the core service provider type APIService struct { // controllerRegistry is where all registered controllers exist controllerRegistry map[string]interface{} //registeredPathAndController is a mapping of paths and controllers registeredPathAndController map[string]map[string]map[string]string requestForm map[string]url.Values } func (api *APIService) Get(path, controllerWithActionString string) { mapping := api.mappingRequestMethodWithControllerAndActions(GETMethod, path, controllerWithActionString) api.registeredPathAndController[path] = mapping } func (api *APIService) Post(path, controllerWithActionString string) { mapping := api.mappingRequestMethodWithControllerAndActions(POSTMethod, path, controllerWithActionString) api.registeredPathAndController[path] = mapping } func (api *APIService) Put(path, controllerWithActionString string) { mapping := api.mappingRequestMethodWithControllerAndActions(PUTMethod, path, controllerWithActionString) api.registeredPathAndController[path] = mapping } func (api *APIService) Patch(path, controllerWithActionString string) { mapping := api.mappingRequestMethodWithControllerAndActions(PATCHMethod, path, controllerWithActionString) api.registeredPathAndController[path] = mapping } func (api *APIService) Options(path, controllerWithActionString string) { mapping := api.mappingRequestMethodWithControllerAndActions(OPTIONSMethod, path, controllerWithActionString) api.registeredPathAndController[path] = mapping } func (api *APIService) Delete(path, controllerWithActionString string) { mapping := api.mappingRequestMethodWithControllerAndActions(DELETEMethod, path, controllerWithActionString) api.registeredPathAndController[path] = mapping } // mappingRequestMethodWithControllerAndActions is a function for mapping request method with controllers // which containing actions func (api *APIService) mappingRequestMethodWithControllerAndActions(requestMethod, path, controllerWithActionString string) map[string]map[string]string { mappingResult := make(map[string]map[string]string) if length := len(api.registeredPathAndController[path]); length > 0 { mappingResult = api.registeredPathAndController[path] } controllerAndActionSlice := strings.Split(controllerWithActionString, "@") controller := controllerAndActionSlice[0] action := controllerAndActionSlice[1] controllerAndActionMap := map[string]string{controller: action} mappingResult[requestMethod] = controllerAndActionMap return mappingResult } // HandleRequest is a function to handle http request func (api *APIService) HandleRequest(controllers map[string]map[string]string) http.HandlerFunc { return func(rw http.ResponseWriter, request *http.Request) { request.ParseForm() method := request.Method api.requestForm["query"] = request.Form api.requestForm["form"] = request.PostForm macthedControllers, ok := controllers[method] if !ok { rw.WriteHeader(HTTPMethodNotAllowed) } for k, v := range macthedControllers { controllerKey := "*" + k controller := api.controllerRegistry[controllerKey] in := make([]reflect.Value, 2) in[0] = reflect.ValueOf(api.requestForm) in[1] = reflect.ValueOf(request.Header) returnValues := reflect.ValueOf(controller).MethodByName(v).Call(in) statusCode := returnValues[0].Interface() intStatusCode := statusCode.(int) response := returnValues[1].Interface() responseHeaders := http.Header{} if len(returnValues) == 3 { responseHeaders = returnValues[2].Interface().(http.Header) } api.JSONResponse(rw, intStatusCode, response, responseHeaders) } } } // RegisterHandleFunc is a function registers a handle function to handle request from path func (api *APIService) RegisterHandleFunc() { for k, v := range api.registeredPathAndController { path := k if !strings.HasPrefix(k, "/") { path = fmt.Sprintf("/%v", k) } http.HandleFunc(path, api.HandleRequest(v)) } } // RegisterControllers is a function registers a struct of controllers into controllerRegistry func (api *APIService) RegisterControllers(controllers []interface{}) { for _, v := range controllers { api.RegisterController(v) } } // RegisterControllers is a function registers a controller into controllerRegistry func (api *APIService) RegisterController(controller interface{}) { controllerType := getType(controller) api.controllerRegistry[controllerType] = controller } // getType is a function gets the type of value func getType(value interface{}) string { if t := reflect.TypeOf(value); t.Kind() == reflect.Ptr { return "*" + t.Elem().Name() } else { return t.Name() } } // Serve is a function func (api *APIService) Serve(port int) { api.RegisterHandleFunc() fullPort := fmt.Sprintf(":%d", port) http.ListenAndServe(fullPort, nil) } // JSONResponse is a function return json response func (api *APIService) JSONResponse(rw http.ResponseWriter, statusCode int, response interface{}, headers http.Header) { for k, v := range headers { for _, header := range v { rw.Header().Add(k, header) } } rw.Header().Add("Content-Type", "application/json") rw.WriteHeader(statusCode) rsp, err := json.Marshal(response) if err != nil { // TODO: logging error fmt.Println("JSON err:", err) } rw.Write(rsp) } // Prepare is a fucntion prepare the service and return prepared service to the user func Prepare() *APIService { var apiService = new(APIService) apiService.controllerRegistry = make(map[string]interface{}) apiService.registeredPathAndController = make(map[string]map[string]map[string]string) apiService.requestForm = make(map[string]url.Values) return apiService }
關于“golang如何實現一個restful微服務的操作”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。