github.com/fortexxx/gqlgen@v0.10.3-0.20191216030626-ca5ea8b21ead/example/fileupload/server/server.go (about) 1 package main 2 3 import ( 4 "context" 5 "errors" 6 "io/ioutil" 7 "log" 8 "net/http" 9 10 "github.com/99designs/gqlgen/graphql/handler/transport" 11 12 "github.com/99designs/gqlgen/graphql/playground" 13 14 "github.com/99designs/gqlgen/example/fileupload" 15 "github.com/99designs/gqlgen/example/fileupload/model" 16 "github.com/99designs/gqlgen/graphql" 17 "github.com/99designs/gqlgen/graphql/handler" 18 ) 19 20 func main() { 21 http.Handle("/", playground.Handler("File Upload Demo", "/query")) 22 resolver := getResolver() 23 24 var mb int64 = 1 << 20 25 26 srv := handler.New(fileupload.NewExecutableSchema(fileupload.Config{Resolvers: resolver})) 27 28 srv.AddTransport(transport.MultipartForm{ 29 MaxMemory: 32 * mb, 30 MaxUploadSize: 50 * mb, 31 }) 32 33 http.Handle("/query", srv) 34 log.Print("connect to http://localhost:8087/ for GraphQL playground") 35 log.Fatal(http.ListenAndServe(":8087", nil)) 36 } 37 38 func getResolver() *fileupload.Stub { 39 resolver := &fileupload.Stub{} 40 41 resolver.MutationResolver.SingleUpload = func(ctx context.Context, file graphql.Upload) (*model.File, error) { 42 content, err := ioutil.ReadAll(file.File) 43 if err != nil { 44 return nil, err 45 } 46 return &model.File{ 47 ID: 1, 48 Name: file.Filename, 49 Content: string(content), 50 }, nil 51 } 52 resolver.MutationResolver.SingleUploadWithPayload = func(ctx context.Context, req model.UploadFile) (*model.File, error) { 53 content, err := ioutil.ReadAll(req.File.File) 54 if err != nil { 55 return nil, err 56 } 57 return &model.File{ 58 ID: 1, 59 Name: req.File.Filename, 60 Content: string(content), 61 }, nil 62 } 63 resolver.MutationResolver.MultipleUpload = func(ctx context.Context, files []*graphql.Upload) ([]*model.File, error) { 64 if len(files) == 0 { 65 return nil, errors.New("empty list") 66 } 67 var resp []*model.File 68 for i := range files { 69 content, err := ioutil.ReadAll(files[i].File) 70 if err != nil { 71 return []*model.File{}, err 72 } 73 resp = append(resp, &model.File{ 74 ID: i + 1, 75 Name: files[i].Filename, 76 Content: string(content), 77 }) 78 } 79 return resp, nil 80 } 81 resolver.MutationResolver.MultipleUploadWithPayload = func(ctx context.Context, req []*model.UploadFile) ([]*model.File, error) { 82 if len(req) == 0 { 83 return nil, errors.New("empty list") 84 } 85 var resp []*model.File 86 for i := range req { 87 content, err := ioutil.ReadAll(req[i].File.File) 88 if err != nil { 89 return []*model.File{}, err 90 } 91 resp = append(resp, &model.File{ 92 ID: i + 1, 93 Name: req[i].File.Filename, 94 Content: string(content), 95 }) 96 } 97 return resp, nil 98 } 99 return resolver 100 }