GraphQL搭建服务端API

graphql库: github.com/99designs/gqlgen

基于gqlgen加密版: github.com/vndocker/encrypted-graphql

网络框架: github.com/gin-gonic/gin

golang: 1.15.2

项目结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
.
├── go.mod
├── go.sum
├── gqlgen.yml
├── Dockerfile
├── Makefile
├── internal
│ ├── auth
│ │ └── auth.go
│ ├── bff
│ │ └── bff.go #代码生成
│ ├── model
│ │ └── model.go #代码生成
│ ├── resolver
│ │ ├── resolver.go #代码生成
│ │ └── server.resolvers.go #代码生成
│ ├── server
│ │ ├── controller
│ │ │ └── controller.go
│ │ └── server.go
│ └── utils
│ └── utils.go
└── server.graphql

初始化项目

1
2
3
mkdir graphql-server
cd graphql-server
go mod init graphql-server

编写graphql

server.graphql

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# Query
# Response data format
type Token {
value: String!
errors: [ERRORS]
}

# Re:sns
# Response data format
type UserInfo {
info: User!
errors: [ERRORS]
}

type User {
name: String!
birthday: Date!
gender: Int!
genre: [String]
}

type Date {
year: Int!
month: Int!
day: Int!
}

type Like {
status: Boolean!
errors: [ERRORS]
}

type List {
articles: [ArticleHeader]
errors: [ERRORS]
}

type ArticleHeader {
id: String!
title: String!
ImagePath: String!
tags: [String]
}

type Genres {
genres: [String!]
errors: [ERRORS]
}

type Articles {
articles: [ArticleHeader]
errors: [ERRORS]
}

type Article {
info: ArticleInfo
errors: [ERRORS]
}

type ArticleInfo {
title: String!
imagePath: String!
nice: Int!
context: String!
userStatus: ArticleUserInfo
comment: [Comment]
}

type ArticleUserInfo {
nice: Boolean!
list: Boolean!
}

type Comment {
name: String!
image: String!
comment: String!
}

# Response data format
type Log {
log: LogInfo
errors: [ERRORS]
}

type LogInfo {
id: Int!
title: String!
date: String!
worktime: Int!
concentration: [Float!]
}

type Logs {
logs: [LogData]
errors: [ERRORS]
}

type LogData {
id: Int!
title: String!
}

# Response data format
type Spots {
spots: [Spot]
errors: [ERRORS]
}

type Spot {
id: Int!
name: String!
image: String!
description: String!
locate: Locate
}

type Locate {
latitude: Float!
longitude: Float!
}

# Mutation
# Response data format
type Result {
status: Boolean!
errors: [ERRORS]
}

type ERRORS {
code: Int!
message: String!
description: String!
}

# Query List
type Query {
## 用户认证
signin: Token!
# Re:sns
## 获取用户信息
userInfo: UserInfo!
like(articleid: String): Like!
list: List!
## 获取文章
genres: Genres!
articles(genre: String!, year: Int, month: Int): Articles!
article(articleid: String!): Article!
## 获取日志
log(logid: Int!): Log!
logs: Logs!

spots(latitude: Float!, longitude: Float!, worktime: Int!, emotion: Int!): Spots!
}

# Mutation List
type Mutation {
## 用户认证
signup: Token!
# Re:sns
## 注册用户信息
addConstantUserInfo(gender: Int!, year: Int!, month: Int!): Result!
addName(name: String!): Result!
addGenre(genre: [String]!): Result!
## 清单管理
addLike(articleid: String): Result!
addList(articleid: String): Result!
delList(articleid: String): Result!
addRequest(genre: String, year: Int, month: Int, title: String, contents: String): Result!
## 添加评论
addComment(articleid: String, comment: String): Result!

addNewLogData(date: String!, title: String!, worktime: String!, concentration: String!): Result!
addSubscription: Result!

addEvaluation(spotid: Int!, emotion: Int!, value: Int!): Result!
addSpot(name: String!, description: String!, image: [Int!], latitude: Float!, longitude: Float!): Result!
}

# Customer resolver
type Customer {

}

代码生成配置文件

gqlgen.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Where are all the schema files located? globs are supported eg  src/**/*.graphqls
schema:
- ./*.graphql
# Where should the generated server code go?
exec:
filename: internal/bff/bff.go
package: bff
# Uncomment to enable federation
# federation:
# filename: graph/generated/federation.go
# package: generated

# Where should any generated models go?
model:
filename: internal/model/model.go
package: model
# Where should the resolver implementations go?
resolver:
layout: follow-schema
dir: internal/resolver
package: resolver
filename: internal/resolver/resolver.go
# Optional: turn on use `gqlgen:"fieldName"` tags in your models
# struct_tag: json

# Optional: turn on to use []Thing instead of []*Thing
# omit_slice_element_pointers: false

# Optional: set to speed up generation time by not performing a final validation pass.
# skip_validation: true

# gqlgen will search for any type names in the schema in these go packages
# if they match it will use them, otherwise it will generate them.
autobind:
- "graphql-server/internal/model"
# This section declares type mapping between the GraphQL and go type systems
#
# The first line in each type will be used as defaults for resolver arguments and
# modelgen, the others will be allowed when binding to fields. Configure them to
# your liking
models:
ID:
model:
- github.com/99designs/gqlgen/graphql.ID
- github.com/99designs/gqlgen/graphql.Int
- github.com/99designs/gqlgen/graphql.Int64
- github.com/99designs/gqlgen/graphql.Int32
Int:
model:
- github.com/99designs/gqlgen/graphql.Int
- github.com/99designs/gqlgen/graphql.Int64
- github.com/99designs/gqlgen/graphql.Int32

生成代码

1
go run github.com/99designs/gqlgen

鉴权

auth.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package auth

import(
"fmt"
"time"
"io/ioutil"
jwt "github.com/dgrijalva/jwt-go"
)

var(
signKey []byte
)

func init() {
signKey, _ = ioutil.ReadFile("./private.key")
}

func GenerateToken(id string) (string, error) {
token := jwt.New(jwt.SigningMethodHS256)

claims := token.Claims.(jwt.MapClaims)
claims["sub"] = id
claims["iat"] = time.Now()

return token.SignedString(signKey)
}

func VerifyToken(token string) (map[string]interface{}, error) {
t, err := jwt.Parse(token, Hmac)
if err != nil {
return nil, err
}
claims, status := t.Claims.(jwt.MapClaims)
if !(status && t.Valid) {
return nil, fmt.Errorf("[ERROR]: Faild get claims")
}
return claims, nil
}

func Hmac(token *jwt.Token) (interface{}, error) {
if _, status := token.Method.(*jwt.SigningMethodHMAC); !status {
return nil, fmt.Errorf("[ERROR]: Faild Signing Method HMAC")
}
return signKey, nil
}

utils.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package utils

import(
"fmt"
"context"
"graphql-server/internal/model"
)

var(
STATUS_CODE_400 = "Bad Request"
STATUS_CODE_403 = "Forbidden"
STATUS_CODE_500 = "Internal Server Error"
)

func ContextValueChecksum(ctx context.Context, keys ...string) (claims map[string]string, errors []*model.Errors) {
if len(keys) < 1 {
return
}

var value string
var ok bool
claims = make(map[string]string)

for _, key := range keys {
if value, ok = ctx.Value(key).(string); !ok {
errors = append(errors, MakeErrors(500, fmt.Sprintf("Faild get HTTP header value: %s", key)))
}
if value == "" {
errors = append(errors, MakeErrors(400, fmt.Sprintf("HTTP header value is empty: %s", key)))
}
claims[key] = value
}
return
}

func MakeErrors(code int, msg string) (errors *model.Errors) {
switch code {
case 400:
errors = &model.Errors{
Code: 400,
Message: STATUS_CODE_400,
Description: msg,
}
case 403:
errors = &model.Errors{
Code: 403,
Message: STATUS_CODE_403,
Description: msg,
}
case 500:
errors = &model.Errors{
Code: 500,
Message: STATUS_CODE_500,
Description: msg,
}
}
return
}

func CastStringPointer(str string) *string {
return &str
}

服务器

controller.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package controller

import(
"context"
"net/http"
"github.com/gin-gonic/gin"
)

type Controller struct {
PlaygroundServer http.HandlerFunc
QueryServer http.Handler
}

func (ctrl *Controller) PlaygroundHandler(cx *gin.Context) {
ctrl.PlaygroundServer(cx.Writer, cx.Request)
}

func (ctrl *Controller) QueryHandler(cx *gin.Context) {
ctrl.QueryServer.ServeHTTP(cx.Writer, cx.Request)
}

func QueryMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), "id", r.Header.Get("id"))
ctx = context.WithValue(ctx, "pass", r.Header.Get("pass"))
ctx = context.WithValue(ctx, "token", r.Header.Get("token"))
next.ServeHTTP(w, r.WithContext(ctx))
})
}

server.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package main

import(
"os"
"log"
"errors"
"context"
"runtime/debug"
"github.com/gin-gonic/gin"

// generate package
"graphql-server/internal/bff"
"graphql-server/internal/server/controller"
"graphql-server/internal/resolver"

// gql-gen package
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/playground"
)

var port string

func init() {
port = os.Getenv("PORT")
if port == "" {
port = "9020"
}
}

func initializeController() controller.Controller {
srv := handler.NewDefaultServer(bff.NewExecutableSchema(bff.Config{Resolvers: &resolver.Resolver{}}))
srv.SetRecoverFunc(func(ctx context.Context, err interface{}) (userMessage error) {
log.Print(err)
debug.PrintStack()
return errors.New("user message on panic")
})

return controller.Controller{
PlaygroundServer: playground.Handler("GraphQL playground", "/query"),
QueryServer: controller.QueryMiddleware(srv),
}
}

func setupRouter(ctrl controller.Controller) *gin.Engine {
router := gin.Default()
router.GET("/", ctrl.PlaygroundHandler)
router.POST("/query", ctrl.QueryHandler)
return router
}

func main() {
ctrl := initializeController()
router := setupRouter(ctrl)
err := router.Run(":" + port)
if err != nil {
log.Fatalf("failed launch router. err=%s", err)
os.Exit(1)
}
}

实现resolver

server.resolvers.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
package resolver

// This file will be automatically regenerated based on the schema, any resolver implementations
// will be copied through when generating and any unknown code will be moved to the end.

import (
"context"
"graphql-server/internal/auth"
"graphql-server/internal/bff"
"graphql-server/internal/model"
"graphql-server/internal/utils"
"time"
)

func (r *mutationResolver) Signup(ctx context.Context) (*model.Token, error) {
claims, errors := utils.ContextValueChecksum(ctx, "id", "pass")
if len(errors) > 0 {
return &model.Token{
Value: "",
Errors: errors,
}, nil
}

//TODO: Request Auth API
id := claims["id"]

token, err := auth.GenerateToken(id)
if err != nil {
}
return &model.Token{
Value: token,
Errors: []*model.Errors{},
}, nil
}

func (r *mutationResolver) AddConstantUserInfo(ctx context.Context, gender int, year int, month int) (*model.Result, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Result{
Status: false,
Errors: errors,
}, nil
}

return &model.Result{
Status: true,
Errors: errors,
}, nil
}

func (r *mutationResolver) AddName(ctx context.Context, name string) (*model.Result, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Result{
Status: false,
Errors: errors,
}, nil
}

return &model.Result{
Status: true,
Errors: errors,
}, nil
}

func (r *mutationResolver) AddGenre(ctx context.Context, genre []*string) (*model.Result, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Result{
Status: false,
Errors: errors,
}, nil
}

return &model.Result{
Status: true,
Errors: errors,
}, nil
}

func (r *mutationResolver) AddLike(ctx context.Context, articleid *string) (*model.Result, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Result{
Status: false,
Errors: errors,
}, nil
}

return &model.Result{
Status: true,
Errors: errors,
}, nil
}

func (r *mutationResolver) AddList(ctx context.Context, articleid *string) (*model.Result, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Result{
Status: false,
Errors: errors,
}, nil
}

return &model.Result{
Status: true,
Errors: errors,
}, nil
}

func (r *mutationResolver) DelList(ctx context.Context, articleid *string) (*model.Result, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Result{
Status: false,
Errors: errors,
}, nil
}

return &model.Result{
Status: true,
Errors: errors,
}, nil
}

func (r *mutationResolver) AddRequest(ctx context.Context, genre *string, year *int, month *int, title *string, contents *string) (*model.Result, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Result{
Status: false,
Errors: errors,
}, nil
}

return &model.Result{
Status: true,
Errors: errors,
}, nil
}

func (r *mutationResolver) AddComment(ctx context.Context, articleid *string, comment *string) (*model.Result, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Result{
Status: false,
Errors: errors,
}, nil
}

return &model.Result{
Status: true,
Errors: errors,
}, nil
}

func (r *mutationResolver) AddNewLogData(ctx context.Context, date string, title string, worktime string, concentration string) (*model.Result, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Result{
Status: false,
Errors: errors,
}, nil
}

return &model.Result{
Status: true,
Errors: errors,
}, nil
}

func (r *mutationResolver) AddSubscription(ctx context.Context) (*model.Result, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Result{
Status: false,
Errors: errors,
}, nil
}

return &model.Result{
Status: true,
Errors: errors,
}, nil
}

func (r *mutationResolver) AddEvaluation(ctx context.Context, spotid int, emotion int, value int) (*model.Result, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Result{
Status: false,
Errors: errors,
}, nil
}

return &model.Result{
Status: true,
Errors: errors,
}, nil
}

func (r *mutationResolver) AddSpot(ctx context.Context, name string, description string, image []int, latitude float64, longitude float64) (*model.Result, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Result{
Status: false,
Errors: errors,
}, nil
}

return &model.Result{
Status: true,
Errors: errors,
}, nil
}

func (r *queryResolver) Signin(ctx context.Context) (*model.Token, error) {
claims, errors := utils.ContextValueChecksum(ctx, "id", "pass")
if len(errors) > 0 {
return &model.Token{
Value: "",
Errors: errors,
}, nil
}

//TODO: Request Auth API
id := claims["id"]

token, err := auth.GenerateToken(id)
if err != nil {
}
return &model.Token{
Value: token,
Errors: []*model.Errors{},
}, nil
}

func (r *queryResolver) UserInfo(ctx context.Context) (*model.UserInfo, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.UserInfo{
Info: &model.User{},
Errors: errors,
}, nil
}

return &model.UserInfo{
Info: &model.User{
Name: "SaKu",
Birthday: &model.Date{
Year: 9,
Month: 2,
},
Gender: 1,
Genre: []*string {
utils.CastStringPointer("动漫卡通"),
utils.CastStringPointer("电影"),
utils.CastStringPointer("电视剧"),
utils.CastStringPointer("纪录片"),
},
},
Errors: nil,
}, nil
}

func (r *queryResolver) Like(ctx context.Context, articleid *string) (*model.Like, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Like{
Status: false,
Errors: errors,
}, nil
}

return &model.Like{
Status: true,
Errors: nil,
}, nil
}

func (r *queryResolver) List(ctx context.Context) (*model.List, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.List{
Articles: nil,
Errors: errors,
}, nil
}

return &model.List{
Articles: []*model.ArticleHeader{
&model.ArticleHeader{
ID: "114514",
Title: "标题12",
ImagePath: "http://browser9.qhimg.com/bdm/480_296_0/t010824ab8b5cdfa138.jpg",
Tags: []*string{
utils.CastStringPointer("动漫卡通"),
utils.CastStringPointer("电影"),
utils.CastStringPointer("电视剧"),
utils.CastStringPointer("纪录片"),
},
},
},
Errors: nil,
}, nil
}

func (r *queryResolver) Genres(ctx context.Context) (*model.Genres, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Genres{
Genres: nil,
Errors: errors,
}, nil
}

return &model.Genres{
Genres: []string{
"大江东去,浪淘尽,千古风流人物",
"故垒西边,人道是,三国周郎赤壁",
"乱石穿空,惊涛拍岸,卷起千堆雪",
"江山如画,一时多少豪杰",
},
Errors: nil,
}, nil
}

func (r *queryResolver) Articles(ctx context.Context, genre string, year *int, month *int) (*model.Articles, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Articles{
Articles: nil,
Errors: errors,
}, nil
}
if year == nil && month != nil {
return &model.Articles{
Articles: nil,
Errors: []*model.Errors{
utils.MakeErrors(400, "Argment `year` is emptly"),
},
}, nil
}
if year != nil && month == nil {
return &model.Articles{
Articles: nil,
Errors: []*model.Errors{
utils.MakeErrors(400, "Argment `month` is emptly"),
},
}, nil
}

// cast *int to int
// i := *year
// fmt.Println(i)

return &model.Articles{
Articles: []*model.ArticleHeader{
&model.ArticleHeader{
ID: "114514",
Title: "满江红·写怀",
ImagePath: "http://browser9.qhimg.com/bdm/480_296_0/t010824ab8b5cdfa138.jpg",
Tags: []*string{
utils.CastStringPointer("动漫卡通"),
utils.CastStringPointer("电影"),
utils.CastStringPointer("电视剧"),
utils.CastStringPointer("纪录片"),
},
},
},
Errors: nil,
}, nil
}

func (r *queryResolver) Article(ctx context.Context, articleid string) (*model.Article, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Article{
Info: nil,
Errors: errors,
}, nil
}

return &model.Article{
Info: &model.ArticleInfo{
Title: "沁园春·雪",
ImagePath: "http://browser9.qhimg.com/bdm/480_296_0/t010824ab8b5cdfa138.jpg",
Nice: 1919810,
Context: "北国风光,千里冰封,万里雪飘。",
UserStatus: &model.ArticleUserInfo{
Nice: true,
List: true,
},
Comment: []*model.Comment{
&model.Comment{
Name: "SaKu",
Image: "http://browser9.qhimg.com/bdm/480_296_0/t010824ab8b5cdfa138.jpg",
Comment: "一代天骄,成吉思汗,只识弯弓射大雕。",
},
&model.Comment{
Name: "takashi",
Image: "http://browser9.qhimg.com/bdm/480_296_0/t010824ab8b5cdfa138.jpg",
Comment: "俱往矣,数风流人物,还看今朝。",
},
},
},
Errors: errors,
}, nil
}

func (r *queryResolver) Log(ctx context.Context, logid int) (*model.Log, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Log{
Log: nil,
Errors: errors,
}, nil
}

return &model.Log{
Log: &model.LogInfo{
ID: 1919810,
Title: "回眸一笑百媚生,六宫粉黛无颜色",
Date: time.Now().String(),
Worktime: 810,
Concentration: []float64{
11.4,
51.4,
191.9,
81.0,
},
},
Errors: nil,
}, nil
}

func (r *queryResolver) Logs(ctx context.Context) (*model.Logs, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Logs{
Logs: nil,
Errors: errors,
}, nil
}

return &model.Logs{
Logs: []*model.LogData{
&model.LogData{
ID: 114514,
Title: "汉皇重色思倾国,御宇多年求不得",
},
&model.LogData{
ID: 1919,
Title: "杨家有女初长成,养在深闺人未识",
},
&model.LogData{
ID: 810,
Title: "天生丽质难自弃,一朝选在君王侧",
},
},
Errors: errors,
}, nil
}

func (r *queryResolver) Spots(ctx context.Context, latitude float64, longitude float64, worktime int, emotion int) (*model.Spots, error) {
_, errors := utils.ContextValueChecksum(ctx, "token")
if len(errors) > 0 {
return &model.Spots{
Spots: nil,
Errors: errors,
}, nil
}

return &model.Spots{
Spots: []*model.Spot{
&model.Spot{
ID: 114,
Name: "将进酒",
Image: "http://browser9.qhimg.com/bdm/480_296_0/t010824ab8b5cdfa138.jpg",
Description: "君不见,黄河之水天上来,奔流到海不复回。",
Locate: &model.Locate{
Latitude: 24.2705,
Longitude: 122.5557,
},
},
&model.Spot{
ID: 514,
Name: "水调歌头·明月几时有",
Image: "http://browser9.qhimg.com/bdm/480_296_0/t010824ab8b5cdfa138.jpg",
Description: "丙辰中秋,欢饮达旦,大醉,作此篇,兼怀子由。",
Locate: &model.Locate{
Latitude: 24.1659,
Longitude: 153.5912,
},
},
&model.Spot{
ID: 1919,
Name: "桃花源记",
Image: "http://browser9.qhimg.com/bdm/480_296_0/t010824ab8b5cdfa138.jpg",
Description: "晋太元中,武陵人捕鱼为业。缘溪行,忘路之远近。",
Locate: &model.Locate{
Latitude: 20.2531,
Longitude: 136.0411,
},
},
&model.Spot{
ID: 810,
Name: "陋室铭",
Image: "http://browser9.qhimg.com/bdm/480_296_0/t010824ab8b5cdfa138.jpg",
Description: "山不在高,有仙则名。水不在深,有龙则灵。",
Locate: &model.Locate{
Latitude: 45.3326,
Longitude: 148.4508,
},
},
},
Errors: errors,
}, nil
}

// Mutation returns bff.MutationResolver implementation.
func (r *Resolver) Mutation() bff.MutationResolver { return &mutationResolver{r} }

// Query returns bff.QueryResolver implementation.
func (r *Resolver) Query() bff.QueryResolver { return &queryResolver{r} }

type mutationResolver struct{ *Resolver }
type queryResolver struct{ *Resolver }

Makefile

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
GOCMD=go
DOCKERCMD=docker
SSL=openssl genrsa
GO_RUN=$(GOCMD) run
GO_BUILD=$(GOCMD) build
DOCKER_BUILD=$(DOCKERCMD) build
DOCKER_RUN=$(DOCKERCMD) run

TMPGEN= mkdir tmp
DEVDOCKER=config/development/Dockerfile
DEVCONFIG=config/development/gqlgen.yml
GQLGEN=github.com/99designs/gqlgen

all:
$(SSL) -out private.key 4096
clean:
rm private.key
rm -rf internal/bff
rm -rf internal/model
build:
$(GO_RUN) $(GQLGEN)
$(GO_BUILD) -o server internal/server/server.go
run:
$(GO_RUN) internal/server/server.go
docker-build:
$(DOCKER_BUILD) ./ -t graphql-server/bff:0.2.0
docker-run:
$(DOCKER_RUN) -d -p 9020:9020 graphql-server/bff:0.2.0

Dockerfile

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# TODO: Add Docker tasks here.
FROM supinf/golangci-lint:latest AS build-env
WORKDIR /go/src/server/backend-bff
COPY ./ ./
# Install gcc
RUN apk --update add libc-dev
# setup for build API
RUN go get github.com/99designs/gqlgen
RUN go run github.com/99designs/gqlgen
# build API
RUN go build -o server internal/server/server.go

FROM alpine:latest
WORKDIR /usr/local/bin/
RUN apk add --no-cache --update ca-certificates
COPY --from=build-env /go/src/server/backend-bff/server /usr/local/bin/server
COPY --from=build-env /go/src/server/backend-bff/private.key /usr/local/bin/private.key
ENV PORT 9020

EXPOSE 9020
CMD ["/usr/local/bin/server"]

编译运行

1
2
3
cd internal/server
go build
./server

浏览器访问localhost:9020

1
2
3
4
5
6
7
8
9
在生成的model目录下运行
// int:id是整形 string:id是字符串
// []:返回的时列表
go run github.com/vektah/dataloaden SpotLoader int *graphql-server/internal/model.Spot
go run github.com/vektah/dataloaden SpotLoader int []*graphql-server/internal/model.Spot

go run github.com/vektah/dataloaden SpotLoader string *graphql-server/internal/model.Spot
go run github.com/vektah/dataloaden SpotLoader string []*graphql-server/internal/model.Spot

https://github.com/Aristat/golang-example-app/blob/master/resources/graphql/user.graphql

go run github.com/99designs/gqlgen init

//go:generate go run github.com/99designs/gqlgen

https://gocn.vip/topics/10265

https://blog.laisky.com/p/gqlgen/

https://blog.csdn.net/weixin_34163553/article/details/87942150

https://www.cnblogs.com/lhxsoft/p/11902410.html

https://www.sohu.com/a/235978606_205771 干货分享 | GraphQL 数据聚合层

在计算机科学中,内省是指计算机程序在运行时(Run time)检查对象(Object)类型的一种能力,通常也可以称作运行时类型检查。
不应该将内省和反射混淆。相对于内省,反射更进一步,是指计算机程序在运行时(Run time)可以访问、检测和修改它本身状态或行为的一种能力。

https://github.com/oshalygin/gqlgen-pg-todo-example

https://github.com/heron-adroll/dataloader

https://blog.csdn.net/qq_37822034/article/details/106664268

https://github.com/imolorhe/altair graphq客户端多平台