国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁(yè) 后端開(kāi)發(fā) Golang 改進(jìn) Go 微服務(wù)中的請(qǐng)求、驗(yàn)證和響應(yīng)處理

改進(jìn) Go 微服務(wù)中的請(qǐng)求、驗(yàn)證和響應(yīng)處理

Nov 21, 2024 am 09:21 AM

Improving Request, Validation, and Response Handling in Go Microservices

本指南解釋了我如何簡(jiǎn)化 Go 微服務(wù)中請(qǐng)求、驗(yàn)證和響應(yīng)的處理,旨在實(shí)現(xiàn)簡(jiǎn)單性、可重用性和更易于維護(hù)的代碼庫(kù)。

介紹

我在 Go 中使用微服務(wù)已經(jīng)有一段時(shí)間了,我一直很欣賞這種語(yǔ)言提供的清晰度和簡(jiǎn)單性。我最喜歡 Go 的事情之一是幕后沒(méi)有發(fā)生任何事情;代碼始終是透明且可預(yù)測(cè)的。

但是,開(kāi)發(fā)的某些部分可能非常乏味,尤其是在驗(yàn)證和標(biāo)準(zhǔn)化 API 端點(diǎn)中的響應(yīng)時(shí)。我嘗試了許多不同的方法來(lái)解決這個(gè)問(wèn)題,但最近,在編寫(xiě) Go 課程時(shí),我想到了一個(gè)相當(dāng)意想不到的想法。這個(gè)想法給我的訓(xùn)練員增添了一絲“魔力”,令我驚訝的是,我喜歡它。通過(guò)這個(gè)解決方案,我能夠集中請(qǐng)求的驗(yàn)證、解碼和參數(shù)解析的所有邏輯,并統(tǒng)一 API 的編碼和響應(yīng)。最終,我在保持代碼清晰性和減少重復(fù)實(shí)現(xiàn)之間找到了平衡。

問(wèn)題

開(kāi)發(fā) Go 微服務(wù)時(shí),一項(xiàng)常見(jiàn)任務(wù)是有效處理傳入的 HTTP 請(qǐng)求。此過(guò)程通常涉及解析請(qǐng)求主體、提取參數(shù)、驗(yàn)證數(shù)據(jù)以及發(fā)回一致的響應(yīng)。讓我用一個(gè)例子來(lái)說(shuō)明這個(gè)問(wèn)題:

package main

import (
 "encoding/json"
 "github.com/go-chi/chi/v5"
 "github.com/go-chi/chi/v5/middleware"
 "github.com/go-playground/validator/v10"
 "log"
 "net/http"
)

type SampleRequest struct {
 Name string `json:"name" validate:"required,min=3"`
 Age  int    `json:"age" validate:"required,min=1"`
}

var validate = validator.New()

type ValidationErrors struct {
 Errors map[string][]string `json:"errors"`
}

func main() {
 r := chi.NewRouter()
 r.Use(middleware.Logger)
 r.Use(middleware.Recoverer)

 r.Post("/submit/{name}", func(w http.ResponseWriter, r *http.Request) {
  sampleReq := &SampleRequest{}

  // Set the path parameter
  name := chi.URLParam(r, "name")
  if name == "" {
   w.WriteHeader(http.StatusBadRequest)
   json.NewEncoder(w).Encode(map[string]interface{}{
    "code":    http.StatusBadRequest,
    "message": "name is required",
   })
   return
  }
  sampleReq.Name = name

  // Parse and decode the JSON body
  if err := json.NewDecoder(r.Body).Decode(sampleReq); err != nil {
   w.WriteHeader(http.StatusBadRequest)
   json.NewEncoder(w).Encode(map[string]interface{}{
    "code":    http.StatusBadRequest,
    "message": "Invalid JSON format",
   })
   return
  }

  // Validate the request
  if err := validate.Struct(sampleReq); err != nil {
   validationErrors := make(map[string][]string)
   for _, err := range err.(validator.ValidationErrors) {
    fieldName := err.Field()
    validationErrors[fieldName] = append(validationErrors[fieldName], err.Tag())
   }
   w.WriteHeader(http.StatusBadRequest)
   json.NewEncoder(w).Encode(map[string]interface{}{
    "code":    http.StatusBadRequest,
    "message": "Validation error",
    "body":    ValidationErrors{Errors: validationErrors},
   })
   return
  }

  // Send success response
  w.WriteHeader(http.StatusOK)
  json.NewEncoder(w).Encode(map[string]interface{}{
   "code":    http.StatusOK,
   "message": "Request received successfully",
   "body":    sampleReq,
  })
 })

 log.Println("Starting server on :8080")
 http.ListenAndServe(":8080", r)
}

讓我解釋一下上面的代碼,重點(diǎn)是我們手動(dòng)處理的處理程序部分:

  • 處理路徑參數(shù):驗(yàn)證所需的路徑參數(shù)是否存在并處理它。
  • 解碼請(qǐng)求正文:確保正確解析傳入的 JSON。
  • 驗(yàn)證:使用驗(yàn)證器包檢查請(qǐng)求字段是否滿足要求標(biāo)準(zhǔn)。
  • 錯(cuò)誤處理:當(dāng)驗(yàn)證失敗或JSON格式錯(cuò)誤時(shí),用適當(dāng)?shù)腻e(cuò)誤消息響應(yīng)客戶端。
  • 一致的響應(yīng):手動(dòng)構(gòu)建響應(yīng)結(jié)構(gòu)。

雖然代碼有效,但它涉及大量的樣板邏輯,必須為每個(gè)新端點(diǎn)重復(fù)這些邏輯,這使得維護(hù)更加困難并且容易出現(xiàn)不一致。

那么,我們?cè)撊绾胃倪M(jìn)呢?

分解代碼

為了解決這個(gè)問(wèn)題并提高代碼的可維護(hù)性,我決定將邏輯分為三個(gè)不同的層:請(qǐng)求、響應(yīng)驗(yàn)證。這種方法封裝了每個(gè)部分的邏輯,使其可重用且更易于獨(dú)立測(cè)試。

請(qǐng)求層

Request 層負(fù)責(zé)從傳入的 HTTP 請(qǐng)求中解析和提取數(shù)據(jù)。通過(guò)隔離這個(gè)邏輯,我們可以標(biāo)準(zhǔn)化數(shù)據(jù)的處理方式,并確保所有解析得到統(tǒng)一處理。

驗(yàn)證層

驗(yàn)證層僅專注于根據(jù)預(yù)定義規(guī)則驗(yàn)證解析的數(shù)據(jù)。這使驗(yàn)證邏輯與請(qǐng)求處理分開(kāi),使其在不同端點(diǎn)之間更易于維護(hù)和重用。

響應(yīng)層

Response 層處理程序響應(yīng)的構(gòu)造和格式化。通過(guò)集中響應(yīng)邏輯,我們可以確保所有 API 響應(yīng)遵循一致的結(jié)構(gòu),從而簡(jiǎn)化調(diào)試并改進(jìn)客戶端交互。

所以......雖然將代碼分成層可以帶來(lái)諸如可重用性、可測(cè)試性可維護(hù)性之類的好處,但它也帶來(lái)了一些權(quán)衡。復(fù)雜性的增加可能會(huì)使新開(kāi)發(fā)人員更難掌握項(xiàng)目結(jié)構(gòu),而對(duì)于簡(jiǎn)單的端點(diǎn),使用單獨(dú)的層可能會(huì)讓人感覺(jué)過(guò)度,可能會(huì)導(dǎo)致過(guò)度設(shè)計(jì)。了解這些優(yōu)點(diǎn)和缺點(diǎn)有助于決定何時(shí)有效應(yīng)用此模式。

在一天結(jié)束的時(shí)候,總是關(guān)于最困擾你的事情。正確的?所以,現(xiàn)在讓我們介入我們的舊代碼并開(kāi)始實(shí)現(xiàn)上面提到的層。

將代碼重構(gòu)為層

第 1 步:創(chuàng)建請(qǐng)求層

首先,我們重構(gòu)代碼,將請(qǐng)求解析封裝到專用的函數(shù)或模塊中。該層僅專注于讀取和解析請(qǐng)求主體,確保其與處理程序中的其他職責(zé)分離。

創(chuàng)建一個(gè)新文件httpsuite/request.go:

package main

import (
 "encoding/json"
 "github.com/go-chi/chi/v5"
 "github.com/go-chi/chi/v5/middleware"
 "github.com/go-playground/validator/v10"
 "log"
 "net/http"
)

type SampleRequest struct {
 Name string `json:"name" validate:"required,min=3"`
 Age  int    `json:"age" validate:"required,min=1"`
}

var validate = validator.New()

type ValidationErrors struct {
 Errors map[string][]string `json:"errors"`
}

func main() {
 r := chi.NewRouter()
 r.Use(middleware.Logger)
 r.Use(middleware.Recoverer)

 r.Post("/submit/{name}", func(w http.ResponseWriter, r *http.Request) {
  sampleReq := &SampleRequest{}

  // Set the path parameter
  name := chi.URLParam(r, "name")
  if name == "" {
   w.WriteHeader(http.StatusBadRequest)
   json.NewEncoder(w).Encode(map[string]interface{}{
    "code":    http.StatusBadRequest,
    "message": "name is required",
   })
   return
  }
  sampleReq.Name = name

  // Parse and decode the JSON body
  if err := json.NewDecoder(r.Body).Decode(sampleReq); err != nil {
   w.WriteHeader(http.StatusBadRequest)
   json.NewEncoder(w).Encode(map[string]interface{}{
    "code":    http.StatusBadRequest,
    "message": "Invalid JSON format",
   })
   return
  }

  // Validate the request
  if err := validate.Struct(sampleReq); err != nil {
   validationErrors := make(map[string][]string)
   for _, err := range err.(validator.ValidationErrors) {
    fieldName := err.Field()
    validationErrors[fieldName] = append(validationErrors[fieldName], err.Tag())
   }
   w.WriteHeader(http.StatusBadRequest)
   json.NewEncoder(w).Encode(map[string]interface{}{
    "code":    http.StatusBadRequest,
    "message": "Validation error",
    "body":    ValidationErrors{Errors: validationErrors},
   })
   return
  }

  // Send success response
  w.WriteHeader(http.StatusOK)
  json.NewEncoder(w).Encode(map[string]interface{}{
   "code":    http.StatusOK,
   "message": "Request received successfully",
   "body":    sampleReq,
  })
 })

 log.Println("Starting server on :8080")
 http.ListenAndServe(":8080", r)
}

注意:此時(shí),我不得不使用反射。也許我太愚蠢了,找不到更好的等待去做。 ?

當(dāng)然,我們也可以測(cè)試這個(gè),創(chuàng)建測(cè)試文件httpsuite/request_test.go:

package httpsuite

import (
 "encoding/json"
 "errors"
 "github.com/go-chi/chi/v5"
 "net/http"
 "reflect"
)

// RequestParamSetter defines the interface used to set the parameters to the HTTP request object by the request parser.
// Implementing this interface allows custom handling of URL parameters.
type RequestParamSetter interface {
 // SetParam assigns a value to a specified field in the request struct.
 // The fieldName parameter is the name of the field, and value is the value to set.
 SetParam(fieldName, value string) error
}

// ParseRequest parses the incoming HTTP request into a specified struct type, handling JSON decoding and URL parameters.
// It validates the parsed request and returns it along with any potential errors.
// The pathParams variadic argument allows specifying URL parameters to be extracted.
// If an error occurs during parsing, validation, or parameter setting, it responds with an appropriate HTTP status.
func ParseRequest[T RequestParamSetter](w http.ResponseWriter, r *http.Request, pathParams ...string) (T, error) {
 var request T
 var empty T

 defer func() {
  _ = r.Body.Close()
 }()

 if r.Body != http.NoBody {
  if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
   SendResponse[any](w, "Invalid JSON format", http.StatusBadRequest, nil)
   return empty, err
  }
 }

 // If body wasn't parsed request may be nil and cause problems ahead
 if isRequestNil(request) {
  request = reflect.New(reflect.TypeOf(request).Elem()).Interface().(T)
 }

 // Parse URL parameters
 for _, key := range pathParams {
  value := chi.URLParam(r, key)
  if value == "" {
   SendResponse[any](w, "Parameter "+key+" not found in request", http.StatusBadRequest, nil)
   return empty, errors.New("missing parameter: " + key)
  }

  if err := request.SetParam(key, value); err != nil {
   SendResponse[any](w, "Failed to set field "+key, http.StatusInternalServerError, nil)
   return empty, err
  }
 }

 // Validate the combined request struct
 if validationErr := IsRequestValid(request); validationErr != nil {
  SendResponse[ValidationErrors](w, "Validation error", http.StatusBadRequest, validationErr)
  return empty, errors.New("validation error")
 }

 return request, nil
}

func isRequestNil(i interface{}) bool {
 return i == nil || (reflect.ValueOf(i).Kind() == reflect.Ptr && reflect.ValueOf(i).IsNil())
}

如您所見(jiàn),請(qǐng)求層使用驗(yàn)證層。然而,我仍然希望在代碼中保持層的分離,不僅是為了更容易維護(hù),而且因?yàn)槲铱赡苓€想使用隔離的驗(yàn)證層。

根據(jù)需要,將來(lái)我可能會(huì)決定將所有層保持隔離,并通過(guò)使用一些接口來(lái)允許其相互依賴。

第 2 步:實(shí)現(xiàn)驗(yàn)證層

一旦請(qǐng)求解析被分離,我們就創(chuàng)建一個(gè)獨(dú)立的驗(yàn)證函數(shù)或模塊來(lái)處理驗(yàn)證邏輯。通過(guò)隔離此邏輯,我們可以輕松測(cè)試它并跨多個(gè)端點(diǎn)應(yīng)用一致的驗(yàn)證規(guī)則。

為此,我們創(chuàng)建 httpsuite/validation.go 文件:

package main

import (
 "encoding/json"
 "github.com/go-chi/chi/v5"
 "github.com/go-chi/chi/v5/middleware"
 "github.com/go-playground/validator/v10"
 "log"
 "net/http"
)

type SampleRequest struct {
 Name string `json:"name" validate:"required,min=3"`
 Age  int    `json:"age" validate:"required,min=1"`
}

var validate = validator.New()

type ValidationErrors struct {
 Errors map[string][]string `json:"errors"`
}

func main() {
 r := chi.NewRouter()
 r.Use(middleware.Logger)
 r.Use(middleware.Recoverer)

 r.Post("/submit/{name}", func(w http.ResponseWriter, r *http.Request) {
  sampleReq := &SampleRequest{}

  // Set the path parameter
  name := chi.URLParam(r, "name")
  if name == "" {
   w.WriteHeader(http.StatusBadRequest)
   json.NewEncoder(w).Encode(map[string]interface{}{
    "code":    http.StatusBadRequest,
    "message": "name is required",
   })
   return
  }
  sampleReq.Name = name

  // Parse and decode the JSON body
  if err := json.NewDecoder(r.Body).Decode(sampleReq); err != nil {
   w.WriteHeader(http.StatusBadRequest)
   json.NewEncoder(w).Encode(map[string]interface{}{
    "code":    http.StatusBadRequest,
    "message": "Invalid JSON format",
   })
   return
  }

  // Validate the request
  if err := validate.Struct(sampleReq); err != nil {
   validationErrors := make(map[string][]string)
   for _, err := range err.(validator.ValidationErrors) {
    fieldName := err.Field()
    validationErrors[fieldName] = append(validationErrors[fieldName], err.Tag())
   }
   w.WriteHeader(http.StatusBadRequest)
   json.NewEncoder(w).Encode(map[string]interface{}{
    "code":    http.StatusBadRequest,
    "message": "Validation error",
    "body":    ValidationErrors{Errors: validationErrors},
   })
   return
  }

  // Send success response
  w.WriteHeader(http.StatusOK)
  json.NewEncoder(w).Encode(map[string]interface{}{
   "code":    http.StatusOK,
   "message": "Request received successfully",
   "body":    sampleReq,
  })
 })

 log.Println("Starting server on :8080")
 http.ListenAndServe(":8080", r)
}

現(xiàn)在,創(chuàng)建測(cè)試文件httpsuite/validation_test.go:

package httpsuite

import (
 "encoding/json"
 "errors"
 "github.com/go-chi/chi/v5"
 "net/http"
 "reflect"
)

// RequestParamSetter defines the interface used to set the parameters to the HTTP request object by the request parser.
// Implementing this interface allows custom handling of URL parameters.
type RequestParamSetter interface {
 // SetParam assigns a value to a specified field in the request struct.
 // The fieldName parameter is the name of the field, and value is the value to set.
 SetParam(fieldName, value string) error
}

// ParseRequest parses the incoming HTTP request into a specified struct type, handling JSON decoding and URL parameters.
// It validates the parsed request and returns it along with any potential errors.
// The pathParams variadic argument allows specifying URL parameters to be extracted.
// If an error occurs during parsing, validation, or parameter setting, it responds with an appropriate HTTP status.
func ParseRequest[T RequestParamSetter](w http.ResponseWriter, r *http.Request, pathParams ...string) (T, error) {
 var request T
 var empty T

 defer func() {
  _ = r.Body.Close()
 }()

 if r.Body != http.NoBody {
  if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
   SendResponse[any](w, "Invalid JSON format", http.StatusBadRequest, nil)
   return empty, err
  }
 }

 // If body wasn't parsed request may be nil and cause problems ahead
 if isRequestNil(request) {
  request = reflect.New(reflect.TypeOf(request).Elem()).Interface().(T)
 }

 // Parse URL parameters
 for _, key := range pathParams {
  value := chi.URLParam(r, key)
  if value == "" {
   SendResponse[any](w, "Parameter "+key+" not found in request", http.StatusBadRequest, nil)
   return empty, errors.New("missing parameter: " + key)
  }

  if err := request.SetParam(key, value); err != nil {
   SendResponse[any](w, "Failed to set field "+key, http.StatusInternalServerError, nil)
   return empty, err
  }
 }

 // Validate the combined request struct
 if validationErr := IsRequestValid(request); validationErr != nil {
  SendResponse[ValidationErrors](w, "Validation error", http.StatusBadRequest, validationErr)
  return empty, errors.New("validation error")
 }

 return request, nil
}

func isRequestNil(i interface{}) bool {
 return i == nil || (reflect.ValueOf(i).Kind() == reflect.Ptr && reflect.ValueOf(i).IsNil())
}

第 3 步:構(gòu)建響應(yīng)層

最后,我們將響應(yīng)構(gòu)造重構(gòu)為一個(gè)單獨(dú)的模塊。這可確保所有響應(yīng)遵循一致的格式,從而更輕松地管理和調(diào)試整個(gè)應(yīng)用程序中的響應(yīng)。

創(chuàng)建文件httpsuite/response.go:

package httpsuite

import (
 "bytes"
 "context"
 "encoding/json"
 "errors"
 "fmt"
 "github.com/go-chi/chi/v5"
 "github.com/stretchr/testify/assert"
 "log"
 "net/http"
 "net/http/httptest"
 "strconv"
 "strings"
 "testing"
)

// TestRequest includes custom type annotation for UUID
type TestRequest struct {
 ID   int    `json:"id" validate:"required"`
 Name string `json:"name" validate:"required"`
}

func (r *TestRequest) SetParam(fieldName, value string) error {
 switch strings.ToLower(fieldName) {
 case "id":
  id, err := strconv.Atoi(value)
  if err != nil {
   return errors.New("invalid id")
  }
  r.ID = id
 default:
  log.Printf("Parameter %s cannot be set", fieldName)
 }

 return nil
}

func Test_ParseRequest(t *testing.T) {
 testSetURLParam := func(r *http.Request, fieldName, value string) *http.Request {
  ctx := chi.NewRouteContext()
  ctx.URLParams.Add(fieldName, value)
  return r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, ctx))
 }

 type args struct {
  w          http.ResponseWriter
  r          *http.Request
  pathParams []string
 }
 type testCase[T any] struct {
  name    string
  args    args
  want    *TestRequest
  wantErr assert.ErrorAssertionFunc
 }
 tests := []testCase[TestRequest]{
  {
   name: "Successful Request",
   args: args{
    w: httptest.NewRecorder(),
    r: func() *http.Request {
     body, _ := json.Marshal(TestRequest{Name: "Test"})
     req := httptest.NewRequest("POST", "/test/123", bytes.NewBuffer(body))
     req = testSetURLParam(req, "ID", "123")
     req.Header.Set("Content-Type", "application/json")
     return req
    }(),
    pathParams: []string{"ID"},
   },
   want:    &TestRequest{ID: 123, Name: "Test"},
   wantErr: assert.NoError,
  },
  {
   name: "Missing body",
   args: args{
    w: httptest.NewRecorder(),
    r: func() *http.Request {
     req := httptest.NewRequest("POST", "/test/123", nil)
     req = testSetURLParam(req, "ID", "123")
     req.Header.Set("Content-Type", "application/json")
     return req
    }(),
    pathParams: []string{"ID"},
   },
   want:    nil,
   wantErr: assert.Error,
  },
  {
   name: "Missing Path Parameter",
   args: args{
    w: httptest.NewRecorder(),
    r: func() *http.Request {
     req := httptest.NewRequest("POST", "/test", nil)
     req.Header.Set("Content-Type", "application/json")
     return req
    }(),
    pathParams: []string{"ID"},
   },
   want:    nil,
   wantErr: assert.Error,
  },
  {
   name: "Invalid JSON Body",
   args: args{
    w: httptest.NewRecorder(),
    r: func() *http.Request {
     req := httptest.NewRequest("POST", "/test/123", bytes.NewBufferString("{invalid-json}"))
     req = testSetURLParam(req, "ID", "123")
     req.Header.Set("Content-Type", "application/json")
     return req
    }(),
    pathParams: []string{"ID"},
   },
   want:    nil,
   wantErr: assert.Error,
  },
  {
   name: "Validation Error for body",
   args: args{
    w: httptest.NewRecorder(),
    r: func() *http.Request {
     body, _ := json.Marshal(TestRequest{})
     req := httptest.NewRequest("POST", "/test/123", bytes.NewBuffer(body))
     req = testSetURLParam(req, "ID", "123")
     req.Header.Set("Content-Type", "application/json")
     return req
    }(),
    pathParams: []string{"ID"},
   },
   want:    nil,
   wantErr: assert.Error,
  },
  {
   name: "Validation Error for zero ID",
   args: args{
    w: httptest.NewRecorder(),
    r: func() *http.Request {
     body, _ := json.Marshal(TestRequest{Name: "Test"})
     req := httptest.NewRequest("POST", "/test/0", bytes.NewBuffer(body))
     req = testSetURLParam(req, "ID", "0")
     req.Header.Set("Content-Type", "application/json")
     return req
    }(),
    pathParams: []string{"ID"},
   },
   want:    nil,
   wantErr: assert.Error,
  },
 }

 for _, tt := range tests {
  t.Run(tt.name, func(t *testing.T) {
   got, err := ParseRequest[*TestRequest](tt.args.w, tt.args.r, tt.args.pathParams...)
   if !tt.wantErr(t, err, fmt.Sprintf("parseRequest(%v, %v, %v)", tt.args.w, tt.args.r, tt.args.pathParams)) {
    return
   }
   assert.Equalf(t, tt.want, got, "parseRequest(%v, %v, %v)", tt.args.w, tt.args.r, tt.args.pathParams)
  })
 }
}

創(chuàng)建測(cè)試文件httpsuite/response_test.go:

package httpsuite

import (
 "errors"
 "github.com/go-playground/validator/v10"
)

// ValidationErrors represents a collection of validation errors for an HTTP request.
type ValidationErrors struct {
 Errors map[string][]string `json:"errors,omitempty"`
}

// NewValidationErrors creates a new ValidationErrors instance from a given error.
// It extracts field-specific validation errors and maps them for structured output.
func NewValidationErrors(err error) *ValidationErrors {
 var validationErrors validator.ValidationErrors
 errors.As(err, &validationErrors)

 fieldErrors := make(map[string][]string)
 for _, vErr := range validationErrors {
  fieldName := vErr.Field()
  fieldError := fieldName + " " + vErr.Tag()

  fieldErrors[fieldName] = append(fieldErrors[fieldName], fieldError)
 }

 return &ValidationErrors{Errors: fieldErrors}
}

// IsRequestValid validates the provided request struct using the go-playground/validator package.
// It returns a ValidationErrors instance if validation fails, or nil if the request is valid.
func IsRequestValid(request any) *ValidationErrors {
 validate := validator.New(validator.WithRequiredStructEnabled())
 err := validate.Struct(request)
 if err != nil {
  return NewValidationErrors(err)
 }
 return nil
}

此重構(gòu)的每一步都允許我們通過(guò)將特定職責(zé)委托給定義良好的層來(lái)簡(jiǎn)化處理程序邏輯。雖然我不會(huì)在每個(gè)步驟中顯示完整的代碼,但這些更改涉及將解析、驗(yàn)證和響應(yīng)邏輯移動(dòng)到各自的函數(shù)或文件中。

重構(gòu)示例代碼

現(xiàn)在,我們需要更改舊代碼以使用圖層,讓我們看看它會(huì)是什么樣子。

package httpsuite

import (
 "github.com/go-playground/validator/v10"
 "testing"

 "github.com/stretchr/testify/assert"
)

type TestValidationRequest struct {
 Name string `validate:"required"`
 Age  int    `validate:"required,min=18"`
}

func TestNewValidationErrors(t *testing.T) {
 validate := validator.New()
 request := TestValidationRequest{} // Missing required fields to trigger validation errors

 err := validate.Struct(request)
 if err == nil {
  t.Fatal("Expected validation errors, but got none")
 }

 validationErrors := NewValidationErrors(err)

 expectedErrors := map[string][]string{
  "Name": {"Name required"},
  "Age":  {"Age required"},
 }

 assert.Equal(t, expectedErrors, validationErrors.Errors)
}

func TestIsRequestValid(t *testing.T) {
 tests := []struct {
  name           string
  request        TestValidationRequest
  expectedErrors *ValidationErrors
 }{
  {
   name:           "Valid request",
   request:        TestValidationRequest{Name: "Alice", Age: 25},
   expectedErrors: nil, // No errors expected for valid input
  },
  {
   name:    "Missing Name and Age below minimum",
   request: TestValidationRequest{Age: 17},
   expectedErrors: &ValidationErrors{
    Errors: map[string][]string{
     "Name": {"Name required"},
     "Age":  {"Age min"},
    },
   },
  },
  {
   name:    "Missing Age",
   request: TestValidationRequest{Name: "Alice"},
   expectedErrors: &ValidationErrors{
    Errors: map[string][]string{
     "Age": {"Age required"},
    },
   },
  },
 }

 for _, tt := range tests {
  t.Run(tt.name, func(t *testing.T) {
   errs := IsRequestValid(tt.request)
   if tt.expectedErrors == nil {
    assert.Nil(t, errs)
   } else {
    assert.NotNil(t, errs)
    assert.Equal(t, tt.expectedErrors.Errors, errs.Errors)
   }
  })
 }
}

通過(guò)將處理程序代碼重構(gòu)為請(qǐng)求解析、驗(yàn)證和響應(yīng)格式化層,我們成功刪除了之前嵌入處理程序本身的重復(fù)邏輯。這種模塊化方法不僅提高了可讀性,而且通過(guò)保持每個(gè)職責(zé)的重點(diǎn)和可重用性來(lái)增強(qiáng)可維護(hù)性和可測(cè)試性?,F(xiàn)在,處理程序已得到簡(jiǎn)化,開(kāi)發(fā)人員可以輕松理解和修改特定層,而不會(huì)影響整個(gè)流程,從而創(chuàng)建更清晰、更具可擴(kuò)展性的代碼庫(kù)。

結(jié)論

我希望這份關(guān)于使用專用請(qǐng)求、驗(yàn)證和響應(yīng)層構(gòu)建 Go 微服務(wù)的分步指南能夠?yàn)閯?chuàng)建更清晰、更可維護(hù)的代碼提供深入見(jiàn)解。我很想聽(tīng)聽(tīng)您對(duì)這種方法的想法。我錯(cuò)過(guò)了什么重要的事情嗎?您將如何在自己的項(xiàng)目中擴(kuò)展或改進(jìn)這個(gè)想法?

我鼓勵(lì)您探索源代碼并直接在項(xiàng)目中使用httpsuite。您可以在 rluders/httpsuite 存儲(chǔ)庫(kù)中找到該庫(kù)。您的反饋和貢獻(xiàn)對(duì)于使這個(gè)庫(kù)對(duì) Go 社區(qū)更加強(qiáng)大和有用來(lái)說(shuō)非常寶貴。

大家下期見(jiàn)。

以上是改進(jìn) Go 微服務(wù)中的請(qǐng)求、驗(yàn)證和響應(yīng)處理的詳細(xì)內(nèi)容。更多信息請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請(qǐng)聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機(jī)

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開(kāi)發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)代碼編輯軟件(SublimeText3)

默認(rèn)情況下,GO靜態(tài)鏈接的含義是什么? 默認(rèn)情況下,GO靜態(tài)鏈接的含義是什么? Jun 19, 2025 am 01:08 AM

Go默認(rèn)將程序編譯為獨(dú)立二進(jìn)制文件,主要原因是靜態(tài)鏈接。1.部署更簡(jiǎn)單:無(wú)需額外安裝依賴庫(kù),可直接跨Linux發(fā)行版運(yùn)行;2.二進(jìn)制體積更大:包含所有依賴導(dǎo)致文件尺寸增加,但可通過(guò)構(gòu)建標(biāo)志或壓縮工具優(yōu)化;3.更高的可預(yù)測(cè)性與安全性:避免外部庫(kù)版本變化帶來(lái)的風(fēng)險(xiǎn),增強(qiáng)穩(wěn)定性;4.運(yùn)行靈活性受限:無(wú)法熱更新共享庫(kù),需重新編譯部署以修復(fù)依賴漏洞。這些特性使Go適用于CLI工具、微服務(wù)等場(chǎng)景,但在存儲(chǔ)受限或依賴集中管理的環(huán)境中需權(quán)衡取舍。

如何在GO中創(chuàng)建緩沖頻道? (例如,make(chan int,10)) 如何在GO中創(chuàng)建緩沖頻道? (例如,make(chan int,10)) Jun 20, 2025 am 01:07 AM

在Go中創(chuàng)建緩沖通道只需在make函數(shù)中指定容量參數(shù)即可。緩沖通道允許發(fā)送操作在沒(méi)有接收者時(shí)暫存數(shù)據(jù),只要未超過(guò)指定容量,例如ch:=make(chanint,10)創(chuàng)建了一個(gè)可存儲(chǔ)最多10個(gè)整型值的緩沖通道;與無(wú)緩沖通道不同,發(fā)送數(shù)據(jù)時(shí)不會(huì)立即阻塞,而是將數(shù)據(jù)暫存于緩沖區(qū)中,直到被接收者取走;使用時(shí)需注意:1.容量設(shè)置應(yīng)合理以避免內(nèi)存浪費(fèi)或頻繁阻塞;2.需防止緩沖區(qū)無(wú)限堆積數(shù)據(jù)導(dǎo)致內(nèi)存問(wèn)題;3.可用chanstruct{}類型傳遞信號(hào)以節(jié)省資源;常見(jiàn)場(chǎng)景包括控制并發(fā)數(shù)量、生產(chǎn)者-消費(fèi)者模型及異

在沒(méi)有C中的手動(dòng)內(nèi)存管理的情況下,如何確保內(nèi)存安全性? 在沒(méi)有C中的手動(dòng)內(nèi)存管理的情況下,如何確保內(nèi)存安全性? Jun 19, 2025 am 01:11 AM

Goensuresmemorysafetywithoutmanualmanagementthroughautomaticgarbagecollection,nopointerarithmetic,safeconcurrency,andruntimechecks.First,Go’sgarbagecollectorautomaticallyreclaimsunusedmemory,preventingleaksanddanglingpointers.Second,itdisallowspointe

如何使用GO進(jìn)行系統(tǒng)編程任務(wù)? 如何使用GO進(jìn)行系統(tǒng)編程任務(wù)? Jun 19, 2025 am 01:10 AM

Go是系統(tǒng)編程的理想選擇,因?yàn)樗Y(jié)合了C等編譯型語(yǔ)言的性能與現(xiàn)代語(yǔ)言的易用性和安全性。1.文件與目錄操作方面,Go的os包支持創(chuàng)建、刪除、重命名及檢查文件和目錄是否存在,使用os.ReadFile可一行代碼讀取整個(gè)文件,適用于編寫(xiě)備份腳本或日志處理工具;2.進(jìn)程管理方面,通過(guò)os/exec包的exec.Command函數(shù)可執(zhí)行外部命令、捕獲輸出、設(shè)置環(huán)境變量、重定向輸入輸出流以及控制進(jìn)程生命周期,適合用于自動(dòng)化工具和部署腳本;3.網(wǎng)絡(luò)與并發(fā)方面,net包支持TCP/UDP編程、DNS查詢及原始套

如何在GO中的結(jié)構(gòu)實(shí)例上調(diào)用方法? 如何在GO中的結(jié)構(gòu)實(shí)例上調(diào)用方法? Jun 24, 2025 pm 03:17 PM

在Go語(yǔ)言中,調(diào)用結(jié)構(gòu)體方法需先定義結(jié)構(gòu)體和綁定接收者的方法,使用點(diǎn)號(hào)訪問(wèn)。定義結(jié)構(gòu)體Rectangle后,可通過(guò)值接收者或指針接收者聲明方法;1.使用值接收者如func(rRectangle)Area()int,通過(guò)rect.Area()直接調(diào)用;2.若需修改結(jié)構(gòu)體,應(yīng)使用指針接收者如func(r*Rectangle)SetWidth(...),Go會(huì)自動(dòng)處理指針與值的轉(zhuǎn)換;3.嵌入結(jié)構(gòu)體時(shí),內(nèi)嵌結(jié)構(gòu)體的方法會(huì)被提升,可直接通過(guò)外層結(jié)構(gòu)體調(diào)用;4.Go無(wú)需強(qiáng)制使用getter/setter,字

GO中的接口是什么?如何定義它們? GO中的接口是什么?如何定義它們? Jun 22, 2025 pm 03:41 PM

在Go語(yǔ)言中,接口是一種定義行為而不指定實(shí)現(xiàn)方式的類型。接口由方法簽名組成,任何實(shí)現(xiàn)這些方法的類型都自動(dòng)滿足該接口。例如,定義一個(gè)Speaker接口包含Speak()方法,則所有實(shí)現(xiàn)該方法的類型均可視為Speaker。接口適用于編寫(xiě)通用函數(shù)、抽象實(shí)現(xiàn)細(xì)節(jié)和測(cè)試中使用mock對(duì)象。定義接口使用interface關(guān)鍵字并列出方法簽名,無(wú)需顯式聲明類型實(shí)現(xiàn)了接口。常見(jiàn)用例包括日志、格式化、不同數(shù)據(jù)庫(kù)或服務(wù)的抽象,以及通知系統(tǒng)等。例如,Dog和Robot類型均可實(shí)現(xiàn)Speak方法,并傳遞給同一個(gè)Anno

如何在GO中使用字符串軟件包中的字符串函數(shù)? (例如len(),strings.contains(),strings.index(),strings.replaceall()) 如何在GO中使用字符串軟件包中的字符串函數(shù)? (例如len(),strings.contains(),strings.index(),strings.replaceall()) Jun 20, 2025 am 01:06 AM

在Go語(yǔ)言中,字符串操作主要通過(guò)strings包和內(nèi)置函數(shù)實(shí)現(xiàn)。1.strings.Contains()用于判斷字符串是否包含子串,返回布爾值;2.strings.Index()可查找子串首次出現(xiàn)的位置,若不存在則返回-1;3.strings.ReplaceAll()能替換所有匹配的子串,還可通過(guò)strings.Replace()控制替換次數(shù);4.len()函數(shù)用于獲取字符串字節(jié)數(shù)長(zhǎng)度,但處理Unicode時(shí)需注意字符與字節(jié)的區(qū)別。這些功能常用于數(shù)據(jù)過(guò)濾、文本解析及字符串處理等場(chǎng)景。

如何使用IO軟件包在GO中使用輸入和輸出流? 如何使用IO軟件包在GO中使用輸入和輸出流? Jun 20, 2025 am 11:25 AM

TheGoiopackageprovidesinterfaceslikeReaderandWritertohandleI/Ooperationsuniformlyacrosssources.1.io.Reader'sReadmethodenablesreadingfromvarioussourcessuchasfilesorHTTPresponses.2.io.Writer'sWritemethodfacilitateswritingtodestinationslikestandardoutpu

See all articles