在 Go Chat 專案中實際用到的所有對照
| Java | Go |
|---|---|
class Todo | type Todo struct |
public / private | 大寫開頭 / 小寫開頭 |
new Constructor() | NewXxx() function |
this | method receiver (s *Store) |
implements Interface | 隱式(有對應 method 就算) |
ArrayList<T> | []T(slice) |
HashMap<K,V> | map[K]V |
null | nil |
try-catch | if err != nil |
throw new Exception() | return fmt.Errorf() |
finally | defer |
Thread | goroutine(go func()) |
BlockingQueue | channel(chan T) |
synchronized | sync.Mutex |
CompletableFuture | goroutine + channel |
Optional<T> | 多值回傳 (T, error) |
| Spring | Gin |
|---|---|
@RestController | r.GET("/path", handler) |
@GetMapping / @PostMapping | r.GET / r.POST |
@RequestBody | c.ShouldBindJSON(&obj) |
@PathVariable | c.Param("id") |
@RequestParam | c.Query("name") |
ResponseEntity.ok(data) | c.JSON(200, data) |
@RequestMapping("/api") | r.Group("/api") |
HttpServletRequest | *gin.Context |
@Valid / @NotNull | binding:"required" |
| Spring | Gin |
|---|---|
implements Filter | func() gin.HandlerFunc |
chain.doFilter(req, res) | c.Next() |
不呼叫 chain.doFilter | c.Abort() |
request.setAttribute() | c.Set(key, value) |
request.getAttribute() | c.GetString(key) |
antMatchers("/ws").authenticated() | group.Use(JWTAuth()) |
| JPA | GORM |
|---|---|
@Entity | type User struct + struct tag |
@Id @GeneratedValue | gorm:"primaryKey" |
@Column(unique = true) | gorm:"uniqueIndex" |
@JsonIgnore | json:"-" |
repository.save(entity) | DB.Create(&entity) |
repository.findById(id) | DB.First(&entity, id) |
repository.findByUsername(x) | DB.Where("username = ?", x).First(&entity) |
ddl-auto=update | DB.AutoMigrate(&User{}) |
EntityManagerFactory | gorm.Open(postgres.Open(dsn)) |
| Spring | Go |
|---|---|
BCryptPasswordEncoder | bcrypt.GenerateFromPassword |
Jwts.builder().setClaims() | jwt.NewWithClaims(HS256, claims) |
Jwts.parser().parseClaimsJws() | jwt.Parse(token, keyFunc) |
@AuthenticationPrincipal | c.GetFloat64("user_id") |
SecurityContextHolder | gin.Context(request scope) |
ThreadLocal | context 顯式傳遞 |
| Java (Spring WebSocket) | Go (gorilla/websocket) |
|---|---|
@ServerEndpoint | upgrader.Upgrade(w, r, nil) |
@OnMessage | conn.ReadMessage() in readPump goroutine |
@OnClose | defer in readPump |
session.getBasicRemote().sendText() | conn.WriteMessage() in writePump goroutine |
| 容器管理 session | 自己寫 Hub 管理 Client map |
| Spring Boot | Go |
|---|---|
src/main/java/ | cmd/server/(進入點)+ internal/(業務碼) |
com.example.controller | internal/handler/ |
com.example.service | internal/service/ |
com.example.repository | internal/repository/ |
com.example.model | internal/model/ |
application.yml | .env + config/config.go |
pom.xml / build.gradle | go.mod |
@Autowired | 手動傳入(constructor injection) |
| Java | Go |
|---|---|
mvn spring-boot:run | go run ./cmd/server/ |
mvn package | go build -o app.exe ./cmd/server/ |
mvn test | go test ./... |
gradle dependencies | go mod tidy |
| 需要 JVM 才能跑 | 編譯成原生二進位,零依賴 |