├── .gitignore ├── Main.go ├── README.md ├── api └── api.go ├── middleware └── jwt │ └── jwt.go ├── model ├── user.go └── user_ffjson.go └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Binaries for programs and plugins 3 | *.exe 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 15 | .glide/ 16 | 17 | myBlog.db 18 | .vscode/ -------------------------------------------------------------------------------- /Main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | 6 | "JwtDemo/api" 7 | "JwtDemo/middleware/jwt" 8 | ) 9 | 10 | func main() { 11 | r := gin.Default() 12 | r.POST("/login", api.Login) 13 | r.POST("/register", api.RegisterUser) 14 | 15 | taR := r.Group("/data") 16 | taR.Use(jwt.JWTAuth()) 17 | 18 | { 19 | taR.GET("/dataByTime", api.GetDataByTime) 20 | } 21 | r.Run(":8080") 22 | } 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JwtDemo 2 | gin基于JWT实现token令牌功能demo 3 | 4 | 5 | ### 验证功能 6 | #### 注册 7 | ![注册用户](http://img.newtrekwang.me/201818181648-Y.png) 8 | 9 | #### 登录 10 | ![用户登录](http://img.newtrekwang.me/201818181649-1.png) 11 | 12 | #### 请求需要token的接口 13 | 携带刚才的token请求 14 | ![携带token请求结果](http://img.newtrekwang.me/201818181651-P.png) 15 | 16 | 未携带token 17 | 18 | ![未携带token请求结果](http://img.newtrekwang.me/201818181652-y.png) 19 | 20 | 无效token,随意改动刚才token的一个字符请求 21 | 22 | ![无效token请求结果](http://img.newtrekwang.me/201818181653-N.png) 23 | -------------------------------------------------------------------------------- /api/api.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | myjwt "JwtDemo/middleware/jwt" 5 | "JwtDemo/model" 6 | "log" 7 | "net/http" 8 | "time" 9 | 10 | jwtgo "github.com/dgrijalva/jwt-go" 11 | "github.com/gin-gonic/gin" 12 | ) 13 | 14 | // 注册信息 15 | type RegistInfo struct { 16 | // 手机号 17 | Phone string `json:"mobile"` 18 | // 密码 19 | Pwd string `json:"pwd"` 20 | } 21 | 22 | // Register 注册用户 23 | func RegisterUser(c *gin.Context) { 24 | var registerInfo RegistInfo 25 | if c.BindJSON(®isterInfo) == nil { 26 | err := model.Register(registerInfo.Phone, registerInfo.Pwd) 27 | if err == nil { 28 | c.JSON(http.StatusOK, gin.H{ 29 | "status": 0, 30 | "msg": "注册成功!", 31 | }) 32 | } else { 33 | c.JSON(http.StatusOK, gin.H{ 34 | "status": -1, 35 | "msg": "注册失败" + err.Error(), 36 | }) 37 | } 38 | } else { 39 | c.JSON(http.StatusOK, gin.H{ 40 | "status": -1, 41 | "msg": "解析数据失败!", 42 | }) 43 | } 44 | } 45 | 46 | // LoginResult 登录结果结构 47 | type LoginResult struct { 48 | Token string `json:"token"` 49 | model.User 50 | } 51 | 52 | // Login 登录 53 | func Login(c *gin.Context) { 54 | var loginReq model.LoginReq 55 | if c.BindJSON(&loginReq) == nil { 56 | isPass, user, err := model.LoginCheck(loginReq) 57 | if isPass { 58 | generateToken(c, user) 59 | } else { 60 | c.JSON(http.StatusOK, gin.H{ 61 | "status": -1, 62 | "msg": "验证失败," + err.Error(), 63 | }) 64 | } 65 | } else { 66 | c.JSON(http.StatusOK, gin.H{ 67 | "status": -1, 68 | "msg": "json 解析失败", 69 | }) 70 | } 71 | } 72 | 73 | // 生成令牌 74 | func generateToken(c *gin.Context, user model.User) { 75 | j := &myjwt.JWT{ 76 | []byte("newtrekWang"), 77 | } 78 | claims := myjwt.CustomClaims{ 79 | user.Id, 80 | user.Name, 81 | user.Phone, 82 | jwtgo.StandardClaims{ 83 | NotBefore: int64(time.Now().Unix() - 1000), // 签名生效时间 84 | ExpiresAt: int64(time.Now().Unix() + 3600), // 过期时间 一小时 85 | Issuer: "newtrekWang", //签名的发行者 86 | }, 87 | } 88 | 89 | token, err := j.CreateToken(claims) 90 | 91 | if err != nil { 92 | c.JSON(http.StatusOK, gin.H{ 93 | "status": -1, 94 | "msg": err.Error(), 95 | }) 96 | return 97 | } 98 | 99 | log.Println(token) 100 | 101 | data := LoginResult{ 102 | User: user, 103 | Token: token, 104 | } 105 | c.JSON(http.StatusOK, gin.H{ 106 | "status": 0, 107 | "msg": "登录成功!", 108 | "data": data, 109 | }) 110 | return 111 | } 112 | 113 | // GetDataByTime 一个需要token认证的测试接口 114 | func GetDataByTime(c *gin.Context) { 115 | claims := c.MustGet("claims").(*myjwt.CustomClaims) 116 | if claims != nil { 117 | c.JSON(http.StatusOK, gin.H{ 118 | "status": 0, 119 | "msg": "token有效", 120 | "data": claims, 121 | }) 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /middleware/jwt/jwt.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "errors" 5 | "log" 6 | "net/http" 7 | "time" 8 | 9 | "github.com/dgrijalva/jwt-go" 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // JWTAuth 中间件,检查token 14 | func JWTAuth() gin.HandlerFunc { 15 | return func(c *gin.Context) { 16 | token := c.Request.Header.Get("token") 17 | if token == "" { 18 | c.JSON(http.StatusOK, gin.H{ 19 | "status": -1, 20 | "msg": "请求未携带token,无权限访问", 21 | }) 22 | c.Abort() 23 | return 24 | } 25 | 26 | log.Print("get token: ", token) 27 | 28 | j := NewJWT() 29 | // parseToken 解析token包含的信息 30 | claims, err := j.ParseToken(token) 31 | if err != nil { 32 | if err == TokenExpired { 33 | c.JSON(http.StatusOK, gin.H{ 34 | "status": -1, 35 | "msg": "授权已过期", 36 | }) 37 | c.Abort() 38 | return 39 | } 40 | c.JSON(http.StatusOK, gin.H{ 41 | "status": -1, 42 | "msg": err.Error(), 43 | }) 44 | c.Abort() 45 | return 46 | } 47 | // 继续交由下一个路由处理,并将解析出的信息传递下去 48 | c.Set("claims", claims) 49 | } 50 | } 51 | 52 | // JWT 签名结构 53 | type JWT struct { 54 | SigningKey []byte 55 | } 56 | 57 | // 一些常量 58 | var ( 59 | TokenExpired error = errors.New("Token is expired") 60 | TokenNotValidYet error = errors.New("Token not active yet") 61 | TokenMalformed error = errors.New("That's not even a token") 62 | TokenInvalid error = errors.New("Couldn't handle this token:") 63 | SignKey string = "newtrekWang" 64 | ) 65 | 66 | // 载荷,可以加一些自己需要的信息 67 | type CustomClaims struct { 68 | ID string `json:"userId"` 69 | Name string `json:"name"` 70 | Phone string `json:"phone"` 71 | jwt.StandardClaims 72 | } 73 | 74 | // 新建一个jwt实例 75 | func NewJWT() *JWT { 76 | return &JWT{ 77 | []byte(GetSignKey()), 78 | } 79 | } 80 | 81 | // 获取signKey 82 | func GetSignKey() string { 83 | return SignKey 84 | } 85 | 86 | // 这是SignKey 87 | func SetSignKey(key string) string { 88 | SignKey = key 89 | return SignKey 90 | } 91 | 92 | // CreateToken 生成一个token 93 | func (j *JWT) CreateToken(claims CustomClaims) (string, error) { 94 | token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) 95 | return token.SignedString(j.SigningKey) 96 | } 97 | 98 | // 解析Tokne 99 | func (j *JWT) ParseToken(tokenString string) (*CustomClaims, error) { 100 | token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) { 101 | return j.SigningKey, nil 102 | }) 103 | if err != nil { 104 | if ve, ok := err.(*jwt.ValidationError); ok { 105 | if ve.Errors&jwt.ValidationErrorMalformed != 0 { 106 | return nil, TokenMalformed 107 | } else if ve.Errors&jwt.ValidationErrorExpired != 0 { 108 | // Token is expired 109 | return nil, TokenExpired 110 | } else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 { 111 | return nil, TokenNotValidYet 112 | } else { 113 | return nil, TokenInvalid 114 | } 115 | } 116 | } 117 | if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid { 118 | return claims, nil 119 | } 120 | return nil, TokenInvalid 121 | } 122 | 123 | // 更新token 124 | func (j *JWT) RefreshToken(tokenString string) (string, error) { 125 | jwt.TimeFunc = func() time.Time { 126 | return time.Unix(0, 0) 127 | } 128 | token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) { 129 | return j.SigningKey, nil 130 | }) 131 | if err != nil { 132 | return "", err 133 | } 134 | if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid { 135 | jwt.TimeFunc = time.Now 136 | claims.StandardClaims.ExpiresAt = time.Now().Add(1 * time.Hour).Unix() 137 | return j.CreateToken(*claims) 138 | } 139 | return "", TokenInvalid 140 | } 141 | -------------------------------------------------------------------------------- /model/user.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "MyBlog/utils" 5 | "fmt" 6 | "log" 7 | 8 | "github.com/boltdb/bolt" 9 | ) 10 | 11 | const ( 12 | dbName = "myBlog.db" 13 | userBucket = "user" 14 | ) 15 | 16 | // User 用户类 17 | type User struct { 18 | Id string `json:"userId"` 19 | Name string `json:"userName"` 20 | Gender string `json:"gender"` 21 | Phone string `json:"userMobile"` 22 | Pwd string `json:"pwd"` 23 | Permission string `json:"permission"` 24 | } 25 | 26 | // LoginReq 登录请求参数类 27 | type LoginReq struct { 28 | Phone string `json:"mobile"` 29 | Pwd string `json:"pwd"` 30 | } 31 | 32 | // 序列化 33 | func dumpUser(user User) []byte { 34 | dumped, _ := user.MarshalJSON() 35 | return utils.CompressByte(dumped) 36 | } 37 | 38 | // 反序列化 39 | func loadUser(jsonByte []byte) User { 40 | res := User{} 41 | res.UnmarshalJSON(utils.DecompressByte(jsonByte)) 42 | return res 43 | } 44 | 45 | // Register 插入用户,先检查是否存在用户,如果没有则存入 46 | func Register(phone string, pwd string) error { 47 | if CheckUser(phone) { 48 | return fmt.Errorf("用户已存在!") 49 | } 50 | 51 | db, err := bolt.Open(dbName, 0600, nil) 52 | if err != nil { 53 | log.Fatal(err) 54 | } 55 | defer db.Close() 56 | err = db.Update(func(tx *bolt.Tx) error { 57 | bucket, err := tx.CreateBucketIfNotExists([]byte(userBucket)) 58 | if err != nil { 59 | return err 60 | } 61 | uid := utils.UniqueId() 62 | user := User{ 63 | Phone: phone, 64 | Id: uid, 65 | Name: phone, 66 | Pwd: pwd, 67 | Gender: "0", 68 | } 69 | 70 | if user.Phone == "18683668831" { 71 | user.Permission = "1" 72 | } else { 73 | user.Permission = "0" 74 | } 75 | err = bucket.Put([]byte(uid), dumpUser(user)) 76 | return err 77 | }) 78 | 79 | return err 80 | } 81 | 82 | // CheckUser 检查用户是否存在 83 | func CheckUser(phone string) bool { 84 | db, err := bolt.Open(dbName, 0600, nil) 85 | if err != nil { 86 | log.Fatal(err) 87 | } 88 | defer db.Close() 89 | 90 | result := false 91 | 92 | err = db.View(func(tx *bolt.Tx) error { 93 | bucket := tx.Bucket([]byte(userBucket)) 94 | if bucket == nil { 95 | return fmt.Errorf(" userBuket is null") 96 | } 97 | c := bucket.Cursor() 98 | for k, v := c.First(); k != nil; k, v = c.Next() { 99 | userTemp := loadUser(v) 100 | if phone == userTemp.Phone { 101 | result = true 102 | break 103 | } 104 | } 105 | return nil 106 | }) 107 | return result 108 | } 109 | 110 | // LoginCheck 登录验证 111 | func LoginCheck(loginReq LoginReq) (bool, User, error) { 112 | db, err := bolt.Open(dbName, 0600, nil) 113 | if err != nil { 114 | log.Fatal(err) 115 | } 116 | defer db.Close() 117 | 118 | resultUser := User{} 119 | resultBool := false 120 | err = db.View(func(tx *bolt.Tx) error { 121 | bucket := tx.Bucket([]byte(userBucket)) 122 | if bucket == nil { 123 | return fmt.Errorf(" userBuket is null") 124 | } 125 | c := bucket.Cursor() 126 | for k, v := c.First(); k != nil; k, v = c.Next() { 127 | userTemp := loadUser(v) 128 | if loginReq.Phone == userTemp.Phone && loginReq.Pwd == userTemp.Pwd { 129 | resultUser = userTemp 130 | resultBool = true 131 | break 132 | } 133 | } 134 | if !resultBool { 135 | return fmt.Errorf("用户信息错误!") 136 | } else { 137 | return nil 138 | } 139 | }) 140 | return resultBool, resultUser, err 141 | } 142 | 143 | // EditUserReq 更新用户信息数据类 144 | type EditUserReq struct { 145 | UserId string `json:"userId"` 146 | UserName string `json:"userName"` 147 | UserGender string `json:"gender"` 148 | } 149 | 150 | // UpdateUser 更新用户信息 151 | func UpdateUser(editUser EditUserReq) (User, error) { 152 | db, err := bolt.Open(dbName, 0600, nil) 153 | if err != nil { 154 | log.Fatal(err) 155 | } 156 | defer db.Close() 157 | 158 | var result User 159 | err = db.Update(func(tx *bolt.Tx) error { 160 | bucket, err := tx.CreateBucketIfNotExists([]byte(userBucket)) 161 | if err != nil { 162 | return err 163 | } 164 | 165 | v := bucket.Get([]byte(editUser.UserId)) 166 | if v == nil { 167 | return fmt.Errorf("user not exits") 168 | } 169 | 170 | result = loadUser(v) 171 | result.Name = editUser.UserName 172 | result.Gender = editUser.UserGender 173 | return bucket.Put([]byte(result.Id), dumpUser(result)) 174 | }) 175 | 176 | return result, err 177 | } 178 | 179 | //ResetPwd 重置密码 180 | func ResetPwd(mobile string, pwd string) error { 181 | if !CheckUser(mobile) { 182 | return fmt.Errorf("用户不存在!") 183 | } 184 | 185 | db, err := bolt.Open(dbName, 0600, nil) 186 | if err != nil { 187 | log.Fatal(err) 188 | } 189 | defer db.Close() 190 | 191 | err = db.Update(func(tx *bolt.Tx) error { 192 | bucket := tx.Bucket([]byte(userBucket)) 193 | if bucket == nil { 194 | return fmt.Errorf(" userBuket is null") 195 | } 196 | c := bucket.Cursor() 197 | for k, v := c.First(); k != nil; k, v = c.Next() { 198 | userTemp := loadUser(v) 199 | if mobile == userTemp.Phone { 200 | userTemp.Pwd = pwd 201 | return bucket.Put([]byte(userTemp.Id), dumpUser(userTemp)) 202 | } 203 | } 204 | return nil 205 | }) 206 | return err 207 | } 208 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [2018] [newtrekwang] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /model/user_ffjson.go: -------------------------------------------------------------------------------- 1 | // Code generated by ffjson . DO NOT EDIT. 2 | // source: User.go 3 | 4 | package model 5 | 6 | import ( 7 | "bytes" 8 | "fmt" 9 | 10 | fflib "github.com/pquerna/ffjson/fflib/v1" 11 | ) 12 | 13 | // MarshalJSON marshal bytes to json - template 14 | func (j *LoginReq) MarshalJSON() ([]byte, error) { 15 | var buf fflib.Buffer 16 | if j == nil { 17 | buf.WriteString("null") 18 | return buf.Bytes(), nil 19 | } 20 | err := j.MarshalJSONBuf(&buf) 21 | if err != nil { 22 | return nil, err 23 | } 24 | return buf.Bytes(), nil 25 | } 26 | 27 | // MarshalJSONBuf marshal buff to json - template 28 | func (j *LoginReq) MarshalJSONBuf(buf fflib.EncodingBuffer) error { 29 | if j == nil { 30 | buf.WriteString("null") 31 | return nil 32 | } 33 | var err error 34 | var obj []byte 35 | _ = obj 36 | _ = err 37 | buf.WriteString(`{"mobile":`) 38 | fflib.WriteJsonString(buf, string(j.Phone)) 39 | buf.WriteString(`,"pwd":`) 40 | fflib.WriteJsonString(buf, string(j.Pwd)) 41 | buf.WriteByte('}') 42 | return nil 43 | } 44 | 45 | const ( 46 | ffjtLoginReqbase = iota 47 | ffjtLoginReqnosuchkey 48 | 49 | ffjtLoginReqPhone 50 | 51 | ffjtLoginReqPwd 52 | ) 53 | 54 | var ffjKeyLoginReqPhone = []byte("mobile") 55 | 56 | var ffjKeyLoginReqPwd = []byte("pwd") 57 | 58 | // UnmarshalJSON umarshall json - template of ffjson 59 | func (j *LoginReq) UnmarshalJSON(input []byte) error { 60 | fs := fflib.NewFFLexer(input) 61 | return j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) 62 | } 63 | 64 | // UnmarshalJSONFFLexer fast json unmarshall - template ffjson 65 | func (j *LoginReq) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { 66 | var err error 67 | currentKey := ffjtLoginReqbase 68 | _ = currentKey 69 | tok := fflib.FFTok_init 70 | wantedTok := fflib.FFTok_init 71 | 72 | mainparse: 73 | for { 74 | tok = fs.Scan() 75 | // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) 76 | if tok == fflib.FFTok_error { 77 | goto tokerror 78 | } 79 | 80 | switch state { 81 | 82 | case fflib.FFParse_map_start: 83 | if tok != fflib.FFTok_left_bracket { 84 | wantedTok = fflib.FFTok_left_bracket 85 | goto wrongtokenerror 86 | } 87 | state = fflib.FFParse_want_key 88 | continue 89 | 90 | case fflib.FFParse_after_value: 91 | if tok == fflib.FFTok_comma { 92 | state = fflib.FFParse_want_key 93 | } else if tok == fflib.FFTok_right_bracket { 94 | goto done 95 | } else { 96 | wantedTok = fflib.FFTok_comma 97 | goto wrongtokenerror 98 | } 99 | 100 | case fflib.FFParse_want_key: 101 | // json {} ended. goto exit. woo. 102 | if tok == fflib.FFTok_right_bracket { 103 | goto done 104 | } 105 | if tok != fflib.FFTok_string { 106 | wantedTok = fflib.FFTok_string 107 | goto wrongtokenerror 108 | } 109 | 110 | kn := fs.Output.Bytes() 111 | if len(kn) <= 0 { 112 | // "" case. hrm. 113 | currentKey = ffjtLoginReqnosuchkey 114 | state = fflib.FFParse_want_colon 115 | goto mainparse 116 | } else { 117 | switch kn[0] { 118 | 119 | case 'm': 120 | 121 | if bytes.Equal(ffjKeyLoginReqPhone, kn) { 122 | currentKey = ffjtLoginReqPhone 123 | state = fflib.FFParse_want_colon 124 | goto mainparse 125 | } 126 | 127 | case 'p': 128 | 129 | if bytes.Equal(ffjKeyLoginReqPwd, kn) { 130 | currentKey = ffjtLoginReqPwd 131 | state = fflib.FFParse_want_colon 132 | goto mainparse 133 | } 134 | 135 | } 136 | 137 | if fflib.SimpleLetterEqualFold(ffjKeyLoginReqPwd, kn) { 138 | currentKey = ffjtLoginReqPwd 139 | state = fflib.FFParse_want_colon 140 | goto mainparse 141 | } 142 | 143 | if fflib.SimpleLetterEqualFold(ffjKeyLoginReqPhone, kn) { 144 | currentKey = ffjtLoginReqPhone 145 | state = fflib.FFParse_want_colon 146 | goto mainparse 147 | } 148 | 149 | currentKey = ffjtLoginReqnosuchkey 150 | state = fflib.FFParse_want_colon 151 | goto mainparse 152 | } 153 | 154 | case fflib.FFParse_want_colon: 155 | if tok != fflib.FFTok_colon { 156 | wantedTok = fflib.FFTok_colon 157 | goto wrongtokenerror 158 | } 159 | state = fflib.FFParse_want_value 160 | continue 161 | case fflib.FFParse_want_value: 162 | 163 | if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { 164 | switch currentKey { 165 | 166 | case ffjtLoginReqPhone: 167 | goto handle_Phone 168 | 169 | case ffjtLoginReqPwd: 170 | goto handle_Pwd 171 | 172 | case ffjtLoginReqnosuchkey: 173 | err = fs.SkipField(tok) 174 | if err != nil { 175 | return fs.WrapErr(err) 176 | } 177 | state = fflib.FFParse_after_value 178 | goto mainparse 179 | } 180 | } else { 181 | goto wantedvalue 182 | } 183 | } 184 | } 185 | 186 | handle_Phone: 187 | 188 | /* handler: j.Phone type=string kind=string quoted=false*/ 189 | 190 | { 191 | 192 | { 193 | if tok != fflib.FFTok_string && tok != fflib.FFTok_null { 194 | return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) 195 | } 196 | } 197 | 198 | if tok == fflib.FFTok_null { 199 | 200 | } else { 201 | 202 | outBuf := fs.Output.Bytes() 203 | 204 | j.Phone = string(string(outBuf)) 205 | 206 | } 207 | } 208 | 209 | state = fflib.FFParse_after_value 210 | goto mainparse 211 | 212 | handle_Pwd: 213 | 214 | /* handler: j.Pwd type=string kind=string quoted=false*/ 215 | 216 | { 217 | 218 | { 219 | if tok != fflib.FFTok_string && tok != fflib.FFTok_null { 220 | return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) 221 | } 222 | } 223 | 224 | if tok == fflib.FFTok_null { 225 | 226 | } else { 227 | 228 | outBuf := fs.Output.Bytes() 229 | 230 | j.Pwd = string(string(outBuf)) 231 | 232 | } 233 | } 234 | 235 | state = fflib.FFParse_after_value 236 | goto mainparse 237 | 238 | wantedvalue: 239 | return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) 240 | wrongtokenerror: 241 | return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) 242 | tokerror: 243 | if fs.BigError != nil { 244 | return fs.WrapErr(fs.BigError) 245 | } 246 | err = fs.Error.ToError() 247 | if err != nil { 248 | return fs.WrapErr(err) 249 | } 250 | panic("ffjson-generated: unreachable, please report bug.") 251 | done: 252 | 253 | return nil 254 | } 255 | 256 | // MarshalJSON marshal bytes to json - template 257 | func (j *User) MarshalJSON() ([]byte, error) { 258 | var buf fflib.Buffer 259 | if j == nil { 260 | buf.WriteString("null") 261 | return buf.Bytes(), nil 262 | } 263 | err := j.MarshalJSONBuf(&buf) 264 | if err != nil { 265 | return nil, err 266 | } 267 | return buf.Bytes(), nil 268 | } 269 | 270 | // MarshalJSONBuf marshal buff to json - template 271 | func (j *User) MarshalJSONBuf(buf fflib.EncodingBuffer) error { 272 | if j == nil { 273 | buf.WriteString("null") 274 | return nil 275 | } 276 | var err error 277 | var obj []byte 278 | _ = obj 279 | _ = err 280 | buf.WriteString(`{"userId":`) 281 | fflib.WriteJsonString(buf, string(j.Id)) 282 | buf.WriteString(`,"userName":`) 283 | fflib.WriteJsonString(buf, string(j.Name)) 284 | buf.WriteString(`,"gender":`) 285 | fflib.WriteJsonString(buf, string(j.Gender)) 286 | buf.WriteString(`,"userMobile":`) 287 | fflib.WriteJsonString(buf, string(j.Phone)) 288 | buf.WriteString(`,"pwd":`) 289 | fflib.WriteJsonString(buf, string(j.Pwd)) 290 | buf.WriteString(`,"permission":`) 291 | fflib.WriteJsonString(buf, string(j.Permission)) 292 | buf.WriteByte('}') 293 | return nil 294 | } 295 | 296 | const ( 297 | ffjtUserbase = iota 298 | ffjtUsernosuchkey 299 | 300 | ffjtUserId 301 | 302 | ffjtUserName 303 | 304 | ffjtUserGender 305 | 306 | ffjtUserPhone 307 | 308 | ffjtUserPwd 309 | 310 | ffjtUserPermission 311 | ) 312 | 313 | var ffjKeyUserId = []byte("userId") 314 | 315 | var ffjKeyUserName = []byte("userName") 316 | 317 | var ffjKeyUserGender = []byte("gender") 318 | 319 | var ffjKeyUserPhone = []byte("userMobile") 320 | 321 | var ffjKeyUserPwd = []byte("pwd") 322 | 323 | var ffjKeyUserPermission = []byte("permission") 324 | 325 | // UnmarshalJSON umarshall json - template of ffjson 326 | func (j *User) UnmarshalJSON(input []byte) error { 327 | fs := fflib.NewFFLexer(input) 328 | return j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start) 329 | } 330 | 331 | // UnmarshalJSONFFLexer fast json unmarshall - template ffjson 332 | func (j *User) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error { 333 | var err error 334 | currentKey := ffjtUserbase 335 | _ = currentKey 336 | tok := fflib.FFTok_init 337 | wantedTok := fflib.FFTok_init 338 | 339 | mainparse: 340 | for { 341 | tok = fs.Scan() 342 | // println(fmt.Sprintf("debug: tok: %v state: %v", tok, state)) 343 | if tok == fflib.FFTok_error { 344 | goto tokerror 345 | } 346 | 347 | switch state { 348 | 349 | case fflib.FFParse_map_start: 350 | if tok != fflib.FFTok_left_bracket { 351 | wantedTok = fflib.FFTok_left_bracket 352 | goto wrongtokenerror 353 | } 354 | state = fflib.FFParse_want_key 355 | continue 356 | 357 | case fflib.FFParse_after_value: 358 | if tok == fflib.FFTok_comma { 359 | state = fflib.FFParse_want_key 360 | } else if tok == fflib.FFTok_right_bracket { 361 | goto done 362 | } else { 363 | wantedTok = fflib.FFTok_comma 364 | goto wrongtokenerror 365 | } 366 | 367 | case fflib.FFParse_want_key: 368 | // json {} ended. goto exit. woo. 369 | if tok == fflib.FFTok_right_bracket { 370 | goto done 371 | } 372 | if tok != fflib.FFTok_string { 373 | wantedTok = fflib.FFTok_string 374 | goto wrongtokenerror 375 | } 376 | 377 | kn := fs.Output.Bytes() 378 | if len(kn) <= 0 { 379 | // "" case. hrm. 380 | currentKey = ffjtUsernosuchkey 381 | state = fflib.FFParse_want_colon 382 | goto mainparse 383 | } else { 384 | switch kn[0] { 385 | 386 | case 'g': 387 | 388 | if bytes.Equal(ffjKeyUserGender, kn) { 389 | currentKey = ffjtUserGender 390 | state = fflib.FFParse_want_colon 391 | goto mainparse 392 | } 393 | 394 | case 'p': 395 | 396 | if bytes.Equal(ffjKeyUserPwd, kn) { 397 | currentKey = ffjtUserPwd 398 | state = fflib.FFParse_want_colon 399 | goto mainparse 400 | 401 | } else if bytes.Equal(ffjKeyUserPermission, kn) { 402 | currentKey = ffjtUserPermission 403 | state = fflib.FFParse_want_colon 404 | goto mainparse 405 | } 406 | 407 | case 'u': 408 | 409 | if bytes.Equal(ffjKeyUserId, kn) { 410 | currentKey = ffjtUserId 411 | state = fflib.FFParse_want_colon 412 | goto mainparse 413 | 414 | } else if bytes.Equal(ffjKeyUserName, kn) { 415 | currentKey = ffjtUserName 416 | state = fflib.FFParse_want_colon 417 | goto mainparse 418 | 419 | } else if bytes.Equal(ffjKeyUserPhone, kn) { 420 | currentKey = ffjtUserPhone 421 | state = fflib.FFParse_want_colon 422 | goto mainparse 423 | } 424 | 425 | } 426 | 427 | if fflib.EqualFoldRight(ffjKeyUserPermission, kn) { 428 | currentKey = ffjtUserPermission 429 | state = fflib.FFParse_want_colon 430 | goto mainparse 431 | } 432 | 433 | if fflib.SimpleLetterEqualFold(ffjKeyUserPwd, kn) { 434 | currentKey = ffjtUserPwd 435 | state = fflib.FFParse_want_colon 436 | goto mainparse 437 | } 438 | 439 | if fflib.EqualFoldRight(ffjKeyUserPhone, kn) { 440 | currentKey = ffjtUserPhone 441 | state = fflib.FFParse_want_colon 442 | goto mainparse 443 | } 444 | 445 | if fflib.SimpleLetterEqualFold(ffjKeyUserGender, kn) { 446 | currentKey = ffjtUserGender 447 | state = fflib.FFParse_want_colon 448 | goto mainparse 449 | } 450 | 451 | if fflib.EqualFoldRight(ffjKeyUserName, kn) { 452 | currentKey = ffjtUserName 453 | state = fflib.FFParse_want_colon 454 | goto mainparse 455 | } 456 | 457 | if fflib.EqualFoldRight(ffjKeyUserId, kn) { 458 | currentKey = ffjtUserId 459 | state = fflib.FFParse_want_colon 460 | goto mainparse 461 | } 462 | 463 | currentKey = ffjtUsernosuchkey 464 | state = fflib.FFParse_want_colon 465 | goto mainparse 466 | } 467 | 468 | case fflib.FFParse_want_colon: 469 | if tok != fflib.FFTok_colon { 470 | wantedTok = fflib.FFTok_colon 471 | goto wrongtokenerror 472 | } 473 | state = fflib.FFParse_want_value 474 | continue 475 | case fflib.FFParse_want_value: 476 | 477 | if tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null { 478 | switch currentKey { 479 | 480 | case ffjtUserId: 481 | goto handle_Id 482 | 483 | case ffjtUserName: 484 | goto handle_Name 485 | 486 | case ffjtUserGender: 487 | goto handle_Gender 488 | 489 | case ffjtUserPhone: 490 | goto handle_Phone 491 | 492 | case ffjtUserPwd: 493 | goto handle_Pwd 494 | 495 | case ffjtUserPermission: 496 | goto handle_Permission 497 | 498 | case ffjtUsernosuchkey: 499 | err = fs.SkipField(tok) 500 | if err != nil { 501 | return fs.WrapErr(err) 502 | } 503 | state = fflib.FFParse_after_value 504 | goto mainparse 505 | } 506 | } else { 507 | goto wantedvalue 508 | } 509 | } 510 | } 511 | 512 | handle_Id: 513 | 514 | /* handler: j.Id type=string kind=string quoted=false*/ 515 | 516 | { 517 | 518 | { 519 | if tok != fflib.FFTok_string && tok != fflib.FFTok_null { 520 | return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) 521 | } 522 | } 523 | 524 | if tok == fflib.FFTok_null { 525 | 526 | } else { 527 | 528 | outBuf := fs.Output.Bytes() 529 | 530 | j.Id = string(string(outBuf)) 531 | 532 | } 533 | } 534 | 535 | state = fflib.FFParse_after_value 536 | goto mainparse 537 | 538 | handle_Name: 539 | 540 | /* handler: j.Name type=string kind=string quoted=false*/ 541 | 542 | { 543 | 544 | { 545 | if tok != fflib.FFTok_string && tok != fflib.FFTok_null { 546 | return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) 547 | } 548 | } 549 | 550 | if tok == fflib.FFTok_null { 551 | 552 | } else { 553 | 554 | outBuf := fs.Output.Bytes() 555 | 556 | j.Name = string(string(outBuf)) 557 | 558 | } 559 | } 560 | 561 | state = fflib.FFParse_after_value 562 | goto mainparse 563 | 564 | handle_Gender: 565 | 566 | /* handler: j.Gender type=string kind=string quoted=false*/ 567 | 568 | { 569 | 570 | { 571 | if tok != fflib.FFTok_string && tok != fflib.FFTok_null { 572 | return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) 573 | } 574 | } 575 | 576 | if tok == fflib.FFTok_null { 577 | 578 | } else { 579 | 580 | outBuf := fs.Output.Bytes() 581 | 582 | j.Gender = string(string(outBuf)) 583 | 584 | } 585 | } 586 | 587 | state = fflib.FFParse_after_value 588 | goto mainparse 589 | 590 | handle_Phone: 591 | 592 | /* handler: j.Phone type=string kind=string quoted=false*/ 593 | 594 | { 595 | 596 | { 597 | if tok != fflib.FFTok_string && tok != fflib.FFTok_null { 598 | return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) 599 | } 600 | } 601 | 602 | if tok == fflib.FFTok_null { 603 | 604 | } else { 605 | 606 | outBuf := fs.Output.Bytes() 607 | 608 | j.Phone = string(string(outBuf)) 609 | 610 | } 611 | } 612 | 613 | state = fflib.FFParse_after_value 614 | goto mainparse 615 | 616 | handle_Pwd: 617 | 618 | /* handler: j.Pwd type=string kind=string quoted=false*/ 619 | 620 | { 621 | 622 | { 623 | if tok != fflib.FFTok_string && tok != fflib.FFTok_null { 624 | return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) 625 | } 626 | } 627 | 628 | if tok == fflib.FFTok_null { 629 | 630 | } else { 631 | 632 | outBuf := fs.Output.Bytes() 633 | 634 | j.Pwd = string(string(outBuf)) 635 | 636 | } 637 | } 638 | 639 | state = fflib.FFParse_after_value 640 | goto mainparse 641 | 642 | handle_Permission: 643 | 644 | /* handler: j.Permission type=string kind=string quoted=false*/ 645 | 646 | { 647 | 648 | { 649 | if tok != fflib.FFTok_string && tok != fflib.FFTok_null { 650 | return fs.WrapErr(fmt.Errorf("cannot unmarshal %s into Go value for string", tok)) 651 | } 652 | } 653 | 654 | if tok == fflib.FFTok_null { 655 | 656 | } else { 657 | 658 | outBuf := fs.Output.Bytes() 659 | 660 | j.Permission = string(string(outBuf)) 661 | 662 | } 663 | } 664 | 665 | state = fflib.FFParse_after_value 666 | goto mainparse 667 | 668 | wantedvalue: 669 | return fs.WrapErr(fmt.Errorf("wanted value token, but got token: %v", tok)) 670 | wrongtokenerror: 671 | return fs.WrapErr(fmt.Errorf("ffjson: wanted token: %v, but got token: %v output=%s", wantedTok, tok, fs.Output.String())) 672 | tokerror: 673 | if fs.BigError != nil { 674 | return fs.WrapErr(fs.BigError) 675 | } 676 | err = fs.Error.ToError() 677 | if err != nil { 678 | return fs.WrapErr(err) 679 | } 680 | panic("ffjson-generated: unreachable, please report bug.") 681 | done: 682 | 683 | return nil 684 | } 685 | --------------------------------------------------------------------------------