In Go framework development, common problems include the inability to inject dependencies, simulate HTTP requests, and obtain user IDs. This article provides solutions: Inject dependencies: Use gorm.Model to embed the model, create the model in the models package, create the dependencies in the app package, and use wire injection. Mock HTTP requests: Using context and http.Request, create a mock request and test the controller handling the request. Get user ID: Get the information of the currently logged in user from the HTTP request through context and jwt.
Go framework common problems and solutions
In the development of the Go framework, you will encounter some common problems. This article will introduce these problems and their solutions, and provide practical cases.
Problem 1: Unable to inject dependencies
This is one of the most common problems when using the Go framework. To resolve this issue, you can follow these steps:
gorm.Model
. models
package. app
package. wire
to inject dependencies. Practical case:
// models/user.go package models import "gorm.io/gorm" type User struct { gorm.Model Name string }
// app/dependencies.go package app import "github.com/google/wire" var UserRepoSet = wire.NewSet( wire.Struct(new(UserRepository), "*"), wire.Bind(new(UserRepository), new(IUserRepository)), )
Question 2: How to simulate HTTP requests in unit tests
For testing It is critical that the controller handles HTTP requests. For this purpose, context
and http.Request
can be used.
Practical case:
func TestUserController_CreateUser(t *testing.T) { ctx := context.Background() body := strings.NewReader("{\"name\": \"test\"}") req := http.Request{Body: body} userRepo := &userRepositoryMock{ CreateFunc: func(*User) error { return nil }, } ctrl := NewUserController(userRepo) w := httptest.NewRecorder() ctrl.CreateUser(ctx, w, &req) assert.Equal(t, http.StatusCreated, w.Code) }
Question 3: How to get the user ID in the HTTP request
Get the current user ID in the API Login user information is very important. This can be achieved through context
and jwt
.
Practical Example:
func GetUserFromContext(ctx context.Context) (int, error) { claims, ok := ctx.Value("claims").(jwt.MapClaims) if !ok { return 0, errors.New("error getting claims from context") } userID := claims["user_id"].(float64) return int(userID), nil }
By solving these common problems, developers can build robust and testable Go applications.
The above is the detailed content of Golang framework common problems and solutions. For more information, please follow other related articles on the PHP Chinese website!