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