Java → Go Cheatsheet

在 Go Chat 專案中實際用到的所有對照

語言基礎

JavaGo
class Todotype Todo struct
public / private大寫開頭 / 小寫開頭
new Constructor()NewXxx() function
thismethod receiver (s *Store)
implements Interface隱式(有對應 method 就算)
ArrayList<T>[]T(slice)
HashMap<K,V>map[K]V
nullnil
try-catchif err != nil
throw new Exception()return fmt.Errorf()
finallydefer
Threadgoroutinego func()
BlockingQueuechannelchan T
synchronizedsync.Mutex
CompletableFuturegoroutine + channel
Optional<T>多值回傳 (T, error)

HTTP 框架:Spring → Gin

SpringGin
@RestControllerr.GET("/path", handler)
@GetMapping / @PostMappingr.GET / r.POST
@RequestBodyc.ShouldBindJSON(&obj)
@PathVariablec.Param("id")
@RequestParamc.Query("name")
ResponseEntity.ok(data)c.JSON(200, data)
@RequestMapping("/api")r.Group("/api")
HttpServletRequest*gin.Context
@Valid / @NotNullbinding:"required"

Middleware:Filter → gin.HandlerFunc

SpringGin
implements Filterfunc() gin.HandlerFunc
chain.doFilter(req, res)c.Next()
不呼叫 chain.doFilterc.Abort()
request.setAttribute()c.Set(key, value)
request.getAttribute()c.GetString(key)
antMatchers("/ws").authenticated()group.Use(JWTAuth())

ORM:JPA / Hibernate → GORM

JPAGORM
@Entitytype User struct + struct tag
@Id @GeneratedValuegorm:"primaryKey"
@Column(unique = true)gorm:"uniqueIndex"
@JsonIgnorejson:"-"
repository.save(entity)DB.Create(&entity)
repository.findById(id)DB.First(&entity, id)
repository.findByUsername(x)DB.Where("username = ?", x).First(&entity)
ddl-auto=updateDB.AutoMigrate(&User{})
EntityManagerFactorygorm.Open(postgres.Open(dsn))

認證:Spring Security → 手動

SpringGo
BCryptPasswordEncoderbcrypt.GenerateFromPassword
Jwts.builder().setClaims()jwt.NewWithClaims(HS256, claims)
Jwts.parser().parseClaimsJws()jwt.Parse(token, keyFunc)
@AuthenticationPrincipalc.GetFloat64("user_id")
SecurityContextHoldergin.Context(request scope)
ThreadLocalcontext 顯式傳遞

WebSocket

Java (Spring WebSocket)Go (gorilla/websocket)
@ServerEndpointupgrader.Upgrade(w, r, nil)
@OnMessageconn.ReadMessage() in readPump goroutine
@OnClosedefer in readPump
session.getBasicRemote().sendText()conn.WriteMessage() in writePump goroutine
容器管理 session自己寫 Hub 管理 Client map

專案結構

Spring BootGo
src/main/java/cmd/server/(進入點)+ internal/(業務碼)
com.example.controllerinternal/handler/
com.example.serviceinternal/service/
com.example.repositoryinternal/repository/
com.example.modelinternal/model/
application.yml.env + config/config.go
pom.xml / build.gradlego.mod
@Autowired手動傳入(constructor injection)

開發工具

JavaGo
mvn spring-boot:rungo run ./cmd/server/
mvn packagego build -o app.exe ./cmd/server/
mvn testgo test ./...
gradle dependenciesgo mod tidy
需要 JVM 才能跑編譯成原生二進位,零依賴