go-kratos使用备忘
我搭建的一个kratos项目模板,欢迎使用,仓库地址 需要特别注意的一些建议 API路由覆盖的问题 比如有两个接口 A get /v1/user/{user_id}和 B get /v1/user/profile如果A定义在B之前,那么B可能会被A覆盖路由。需要将A放到B之前。 JWT使用的建议 摘自极客时间课程《高并发系统实战课》 通讯过程必须使用 HTTPS 协议,这样才可以降低被拦截的可能。 要注意限制 token 的更换次数,并定期刷新 token,比如用户的 access_token 每天只能更换 50 次,超过了就要求用户重新登陆,同时 token 每隔 15 分钟更换一次。这样可以降低 token 被盗取后给用户带来的影响。 Web 用户的 token 保存在 cookie 中时,建议加上 httponly、SameSite=Strict 限制,以防止 cookie 被一些特殊脚本偷走。 配置文件 配置文件校验 配合buf的validate可以方便地进行配置文件的校验,在程序启动之前就对配置文件进行一次校验。下面是一个简单的proto配置定义 syntax = "proto3"; package conf; import "buf/validate/validate.proto"; import "google/protobuf/duration.proto"; option go_package = "github.com/tpl-x/kratos/internal/conf;conf"; message Bootstrap { Server server = 1; Data data = 2; Log log = 3; } message Server { message HTTP { string network = 1; string addr = 2; google.protobuf.Duration timeout = 3 [ // the field is required (buf.validate.field).required = true, // duration must be longer than 1 second but no longer than 10 min. (buf.validate.field).duration = { // Validates that duration is greater than 1 second gt: {seconds: 1} // Validates that duration is less than or equal to 10 min. lte: {seconds: 600} } ]; } message GRPC { string network = 1; string addr = 2; google.protobuf.Duration timeout = 3 [ // the field is required (buf.validate.field).required = true, // duration must be longer than 1 second but no longer than 10 min. (buf.validate.field).duration = { // Validates that duration is greater than 1 second gt: {seconds: 1} // Validates that duration is less than or equal to 10 min. lte: {seconds: 600} } ]; } HTTP http = 1; GRPC grpc = 2; } message Data { message Database { string driver = 1; string source = 2; } message Redis { string network = 1; string addr = 2; google.protobuf.Duration read_timeout = 3; google.protobuf.Duration write_timeout = 4; } Database database = 1; Redis redis = 2; } enum LogLevel { Debug = 0; Info = 1; Warn = 2; Error = 3; Fatal = 4; } message Log { string log_path = 1; LogLevel log_level = 2 [(buf.validate.field).enum = { defined_only: true in: [ 0, 1, 2, 3, 4 ] }]; int32 max_size = 3; int32 max_keep_days = 4; int32 max_keep_files = 5; bool compress = 6; } 生成proto对应的go文件中以后,就可以通过下面的方式进行校验: ...