このガイドでは、シンプルさ、再利用性、より保守しやすいコードベースを目指して、Go マイクロサービスでのリクエスト、検証、応答の処理をどのように合理化したかについて説明します。
導(dǎo)入
私はかなり長(zhǎng)い間 Go でマイクロサービスを使ってきましたが、この言語(yǔ)が提供する明快さとシンプルさにいつも感謝しています。私が Go で最も気に入っている點(diǎn)の 1 つは、舞臺(tái)裏では何も起こらないことです。コードは常に透過(guò)的で予測(cè)可能です。
ただし、開(kāi)発の一部の部分は、特に API エンドポイントでの応答の検証と標(biāo)準(zhǔn)化に関しては、非常に面倒な場(chǎng)合があります。これに取り組むためにさまざまなアプローチを試してきましたが、最近、囲碁コースを書(shū)いているときに、かなり予想外のアイデアを思いつきました。このアイデアは私のハンドラーにちょっとした「魔法」を加えました。そして、驚いたことに、私はそれを気に入りました。このソリューションにより、リクエストの検証、デコード、パラメータ解析のためのすべてのロジックを一元化し、API のエンコードと応答を統(tǒng)一することができました。最終的に、コードの明瞭性の維持と反復(fù)的な実裝の削減との間のバランスを見(jiàn)つけました。
問(wèn)題
Go マイクロサービスを開(kāi)発するときの一般的なタスクの 1 つは、受信した HTTP リクエストを効率的に処理することです。このプロセスには通常、リクエスト本文の解析、パラメータの抽出、データの検証、一貫した応答の送り返しが含まれます。例を挙げて問(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) }
手動(dòng)で処理するハンドラー部分に焦點(diǎn)を當(dāng)てて、上記のコードを説明します。
- パス パラメーターを処理します: 必要なパス パラメーターが存在するかどうかを確認(rèn)し、それを処理します。
- リクエスト本文のデコード: 受信した JSON が正しく解析されていることを確認(rèn)します。
- 検証: バリデーター パッケージを使用して、リクエスト フィールドが要件基準(zhǔn)を満たしているかどうかを確認(rèn)します。
- エラー処理: 検証が失敗した場(chǎng)合、または JSON の形式が不正な場(chǎng)合に、適切なエラー メッセージでクライアントに応答します。
- 一貫した応答: 応答構(gòu)造を手動(dòng)で構(gòu)築します。
コードは機(jī)能しますが、新しいエンドポイントごとに繰り返す必要がある大量の定型ロジックが含まれるため、保守が難しくなり、不整合が発生しやすくなります。
それでは、どうすればこれを改善できるでしょうか?
コードを分解する
この問(wèn)題に対処し、コードの保守性を向上させるために、ロジックを リクエスト、レスポンス、および 検証の 3 つの異なる層に分割することにしました。このアプローチでは、各部分のロジックがカプセル化され、再利用可能になり、獨(dú)立したテストが容易になります。
リクエスト層
Request レイヤーは、受信した HTTP リクエストからデータを解析して抽出する役割を果たします。このロジックを分離することで、データの処理方法を標(biāo)準(zhǔn)化し、すべての解析が均一に処理されるようにすることができます。
検証層
Validation レイヤーは、事前定義されたルールに従って解析されたデータを検証することだけに焦點(diǎn)を當(dāng)てています。これにより、検証ロジックがリクエスト処理から分離され、さまざまなエンドポイント間での保守性と再利用性が向上します。
応答層
Response レイヤー ハンドラーは、応答の構(gòu)築と書(shū)式設(shè)定を行います。応答ロジックを一元化することで、すべての API 応答が一貫した構(gòu)造に従うようになり、デバッグが簡(jiǎn)素化され、クライアントとの対話が改善されます。
つまり… コードをレイヤーに分割すると、再利用性、テスト容易性、保守性などの利點(diǎn)が得られますが、いくつかのトレードオフも伴います。複雑さが増すと、新しい開(kāi)発者にとってプロジェクトの構(gòu)造が理解しにくくなる可能性があり、単純なエンドポイントの場(chǎng)合、個(gè)別のレイヤーを使用するのは過(guò)剰に感じられ、オーバーエンジニアリングにつながる可能性があります。これらの長(zhǎng)所と短所を理解することは、このパターンをいつ効果的に適用するかを決定するのに役立ちます。
一日の終わりに気になるのは、いつも自分が一番悩んでいることです。右?そこで、古いコードに手を加えて、上記のレイヤーの実裝を開(kāi)始しましょう。
コードをレイヤーにリファクタリングする
ステップ 1: リクエストレイヤーの作成
まず、コードをリファクタリングして、リクエスト解析を?qū)熡盲伍v數(shù)またはモジュールにカプセル化します。この層はリクエスト本文の読み取りと解析のみに重點(diǎn)を置き、ハンドラー內(nèi)の他の役割から確実に切り離されます。
新しいファイルを作成します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í)點(diǎn)では、リフレクションを使用する必要がありました。おそらく私はもっと愚かで、もっと良い方法を見(jiàn)つけるのを待つしかないでしょう。 ?
もちろん、これをテストすることもできるので、テスト ファイル 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()) }
ご覧のとおり、Request レイヤーは Validation レイヤーを使用します。ただし、メンテナンスを容易にするためだけでなく、検証レイヤーも分離して使用したい場(chǎng)合があるため、コード內(nèi)でレイヤーを分離しておきたいと考えています。
將來(lái)的には、ニーズに応じて、すべてのレイヤーを分離し、いくつかのインターフェイスを使用して相互依存関係を許可することを決定する可能性があります。
ステップ 2: 検証レイヤーの実裝
リクエストの解析が分離されたら、検証ロジックを処理するスタンドアロンの検証関數(shù)またはモジュールを作成します。このロジックを分離することで、簡(jiǎn)単にテストし、複數(shù)のエンドポイントに一貫した検証ルールを適用できます。
そのために、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) }
次に、テスト ファイル 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)築
最後に、応答構(gòu)築を別のモジュールにリファクタリングします。これにより、すべての応答が一貫した形式に従うようになり、アプリケーション全體での応答の管理とデバッグが容易になります。
ファイル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) }) } }
テストファイルを作成します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 }
このリファクタリングの各ステップでは、明確に定義されたレイヤーに特定の責(zé)任を委任することで、ハンドラー ロジックを簡(jiǎn)素化できます。すべてのステップで完全なコードを示すわけではありませんが、これらの変更には、解析、検証、応答ロジックをそれぞれの関數(shù)またはファイルに移動(dòng)することが含まれます。
サンプルコードのリファクタリング
ここで、レイヤーを使用するように古いコードを変更する必要があります。それがどのようになるかを見(jiàn)てみましょう。
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) } }) } }
ハンドラー コードをリクエストの解析、検証、応答の書(shū)式設(shè)定のためのレイヤーにリファクタリングすることにより、ハンドラー自體に以前埋め込まれていた反復(fù)的なロジックを削除することに成功しました。このモジュール式アプローチにより、読みやすさが向上するだけでなく、各責(zé)任に焦點(diǎn)を當(dāng)てて再利用可能にすることで、保守性とテスト容易性も向上します。ハンドラーが簡(jiǎn)素化されたことで、開(kāi)発者はフロー全體に影響を與えることなく特定のレイヤーを簡(jiǎn)単に理解し、変更できるようになり、よりクリーンでスケーラブルなコードベースを作成できます。
結(jié)論
専用のリクエスト、検証、および応答レイヤーを使用して Go マイクロサービスを構(gòu)築するためのこのステップバイステップ ガイドが、よりクリーンで保守しやすいコードを作成するための洞察を提供できれば幸いです。このアプローチについてのご意見(jiàn)をぜひお聞きしたいです。何か重要なことを見(jiàn)逃しているでしょうか?あなた自身のプロジェクトでこのアイデアをどのように拡張または改善しますか?
ソース コードを調(diào)べて、プロジェクト內(nèi)で httpsuite を直接使用することをお?jiǎng)幛幛筏蓼埂¥长违楗ぅ芝楗辘?、rluders/httpsuite リポジトリにあります。このライブラリをさらに堅(jiān)牢で Go コミュニティにとって役立つものにするために、皆様のフィードバックと貢獻(xiàn)が非常に貴重です。
次回でお會(huì)いしましょう。
以上がGo マイクロサービスでのリクエスト、検証、レスポンス処理の改善の詳細(xì)內(nèi)容です。詳細(xì)については、PHP 中國(guó)語(yǔ) Web サイトの他の関連記事を參照してください。

ホットAIツール

Undress AI Tool
脫衣畫(huà)像を無(wú)料で

Undresser.AI Undress
リアルなヌード寫(xiě)真を作成する AI 搭載アプリ

AI Clothes Remover
寫(xiě)真から衣服を削除するオンライン AI ツール。

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無(wú)料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡(jiǎn)単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無(wú)料のコードエディター

SublimeText3 中國(guó)語(yǔ)版
中國(guó)語(yǔ)版、とても使いやすい

ゼンドスタジオ 13.0.1
強(qiáng)力な PHP 統(tǒng)合開(kāi)発環(huán)境

ドリームウィーバー CS6
ビジュアル Web 開(kāi)発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック

Golangは主にバックエンド開(kāi)発に使用されますが、フロントエンドフィールドで間接的な役割を果たすこともできます。その設(shè)計(jì)目標(biāo)は、高性能、同時(shí)処理、システムレベルのプログラミングに焦點(diǎn)を當(dāng)てており、APIサーバー、マイクロサービス、分散システム、データベース操作、CLIツールなどのバックエンドアプリケーションの構(gòu)築に適しています。 GolangはWebフロントエンドの主流言語(yǔ)ではありませんが、Gopherjsを介してJavaScriptにコンパイルしたり、Tinygoを介してWebAssemblyで実行したり、テンプレートエンジンを備えたHTMLページを生成してフロントエンド開(kāi)発に參加できます。ただし、最新のフロントエンド開(kāi)発は、JavaScript/TypeScriptとそのエコシステムに依存する必要があります。したがって、Golangは、コアとして高性能バックエンドを備えたテクノロジースタック選択により適しています。

GOでGraphQlapiを構(gòu)築するには、GQLGenライブラリを使用して開(kāi)発効率を向上させることをお?jiǎng)幛幛筏蓼埂?1.最初に、スキーマに基づいた自動(dòng)コード生成をサポートするGQLGENなどの適切なライブラリを選択します。 2。次に、graphqlschemaを定義し、投稿の種類やクエリメソッドの定義など、API構(gòu)造とクエリポータルを説明します。 3。次に、プロジェクトを初期化し、基本コードを生成して、リゾルバにビジネスロジックを?qū)g裝します。 4.最後に、graphqlhandlerをhttpserverに接続し、組み込みの遊び場(chǎng)を介してAPIをテストします。メモには、プロジェクトのメンテナンスを確保するためのフィールドネーミング仕様、エラー処理、パフォーマンスの最適化、セキュリティ設(shè)定が含まれます

GOをインストールするための鍵は、正しいバージョンを選択し、環(huán)境変數(shù)を構(gòu)成し、インストールを検証することです。 1.公式Webサイトにアクセスして、対応するシステムのインストールパッケージをダウンロードします。 Windowsは.msiファイルを使用し、macosは.pkgファイルを使用し、Linuxは.tar.gzファイルを使用し、 /usr /localディレクトリに解凍します。 2.環(huán)境変數(shù)を構(gòu)成し、linux/macOSで?/.bashrcまたは?/.zshrcを編集してパスとgopathを追加し、Windowsがシステムプロパティに移動(dòng)するパスを設(shè)定します。 3.政府コマンドを使用してインストールを確認(rèn)し、テストプログラムを?qū)g行してhello.goを?qū)g行して、編集と実行が正常であることを確認(rèn)します。プロセス全體のパス設(shè)定とループ

sync.waitgroupは、ゴルチンのグループがタスクを完了するのを待つために使用されます。そのコアは、3つの方法で協(xié)力することです。追加、完了、待機(jī)です。 1.ADD(n)待機(jī)するゴルチンの數(shù)を設(shè)定します。 2.done()は各ゴルチンの端で呼び出され、カウントは1つ減少します。 3.wait()すべてのタスクが完了するまでメインコルーチンをブロックします。使用する場(chǎng)合は、注意してください。Goroutineの外部で追加する必要があります。重複を避け、Donが呼び出されていることを確認(rèn)してください。 Deferで使用することをお?jiǎng)幛幛筏蓼?。これは、Webページの同時(shí)クロール、バッチデータ処理、その他のシナリオで一般的であり、並行性プロセスを効果的に制御できます。

Goの埋め込みパッケージを使用すると、靜的リソースをバイナリに簡(jiǎn)単に埋め込み、Webサービスに適しており、HTML、CSS、寫(xiě)真、その他のファイルをパッケージ化できます。 1。追加する埋め込みリソースを宣言します// go:embed comment hello.txtを埋め込むなど、変數(shù)の前に埋め込みます。 2。static/*などのディレクトリ全體に埋め込み、embed.fsを介してマルチファイルパッケージを?qū)g現(xiàn)できます。 3.効率を改善するために、ビルドタグまたは環(huán)境変數(shù)を介してディスクロードモードを切り替えることをお?jiǎng)幛幛筏蓼埂?4.パスの精度、ファイルサイズの制限、埋め込みリソースの読み取り専用特性に注意してください。埋め込みの合理的な使用は、展開(kāi)を簡(jiǎn)素化し、プロジェクト構(gòu)造を最適化することができます。

オーディオとビデオ?jiǎng)I理の中核は、基本的なプロセスと最適化方法を理解することにあります。 1.基本的なプロセスには、取得、エンコード、送信、デコード、再生が含まれ、各リンクには技術(shù)的な困難があります。 2。オーディオおよびビデオの異常、遅延、音のノイズ、ぼやけた畫(huà)像などの一般的な問(wèn)題は、同期調(diào)整、コーディング最適化、ノイズ減少モジュール、パラメーター調(diào)整などを通じて解決できます。 3. FFMPEG、OPENCV、WeBRTC、GSTREAMER、およびその他のツールを使用して機(jī)能を達(dá)成することをお?jiǎng)幛幛筏蓼埂?4.パフォーマンス管理の観點(diǎn)から、ハードウェアの加速、解像度フレームレートの合理的な設(shè)定、並行性の制御、およびメモリの漏れの問(wèn)題に注意を払う必要があります。これらの重要なポイントを習(xí)得すると、開(kāi)発効率とユーザーエクスペリエンスの向上に役立ちます。

GOで書(shū)かれたWebサーバーを構(gòu)築することは難しくありません。コアは、Net/HTTPパッケージを使用して基本サービスを?qū)g裝することにあります。 1. Net/HTTPを使用して最もシンプルなサーバーを起動(dòng)します。処理機(jī)能を登録し、數(shù)行のコードを介してポートをリッスンします。 2。ルーティング管理:Servemuxを使用して、構(gòu)造化された管理を容易にするために複數(shù)のインターフェイスパスを整理します。 3。共通の実踐:機(jī)能モジュールによるグループルーティング、およびサードパーティライブラリを使用して複雑なマッチングをサポートします。 4.靜的ファイルサービス:http.fileserverを介してHTML、CSS、JSファイルを提供します。 5。パフォーマンスとセキュリティ:HTTPSを有効にし、リクエスト本體のサイズを制限し、セキュリティとパフォーマンスを改善するためのタイムアウトを設(shè)定します。これらの重要なポイントを習(xí)得した後、機(jī)能を拡大する方が簡(jiǎn)単になります。

Select Plusのデフォルトの目的は、他のブランチがプログラムブロッキングを避ける準(zhǔn)備ができていない場(chǎng)合にデフォルトの動(dòng)作を?qū)g行できるようにすることです。 1.ブロックせずにチャネルからデータを受信すると、チャネルが空の場(chǎng)合、デフォルトのブランチに直接入力されます。 2。時(shí)間と組み合わせて。後またはティッカー、定期的にデータを送信してみてください。チャネルがいっぱいの場(chǎng)合、ブロックしてスキップしません。 3.デッドロックを防ぎ、チャネルが閉じられているかどうかが不確かなときにプログラムが詰まっていることを避けます。それを使用する場(chǎng)合、デフォルトのブランチはすぐに実行され、亂用することはできず、デフォルトとケースは相互に排他的であり、同時(shí)に実行されないことに注意してください。
