github.com/thetreep/go-swagger@v0.0.0-20240223100711-35af64f14f01/examples/tutorials/todo-list/server-complete/restapi/configure_todo_list.go (about) 1 // This file is safe to edit. Once it exists it will not be overwritten 2 3 package restapi 4 5 import ( 6 "crypto/tls" 7 "fmt" 8 "net/http" 9 "sync" 10 "sync/atomic" 11 12 errors "github.com/go-openapi/errors" 13 runtime "github.com/go-openapi/runtime" 14 middleware "github.com/go-openapi/runtime/middleware" 15 "github.com/go-openapi/swag" 16 17 "github.com/thetreep/go-swagger/examples/tutorials/todo-list/server-complete/models" 18 "github.com/thetreep/go-swagger/examples/tutorials/todo-list/server-complete/restapi/operations" 19 "github.com/thetreep/go-swagger/examples/tutorials/todo-list/server-complete/restapi/operations/todos" 20 ) 21 22 // This file is safe to edit. Once it exists it will not be overwritten 23 24 var exampleFlags = struct { 25 Example1 string `long:"example1" description:"Sample for showing how to configure cmd-line flags"` 26 Example2 string `long:"example2" description:"Further info at https://github.com/jessevdk/go-flags"` 27 }{} 28 29 func configureFlags(api *operations.TodoListAPI) { 30 api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ 31 { 32 ShortDescription: "Example Flags", 33 LongDescription: "", 34 Options: &exampleFlags, 35 }, 36 } 37 } 38 39 var items = make(map[int64]*models.Item) 40 var lastID int64 41 42 var itemsLock = &sync.Mutex{} 43 44 func newItemID() int64 { 45 return atomic.AddInt64(&lastID, 1) 46 } 47 48 func addItem(item *models.Item) error { 49 if item == nil { 50 return errors.New(500, "item must be present") 51 } 52 53 itemsLock.Lock() 54 defer itemsLock.Unlock() 55 56 newID := newItemID() 57 item.ID = newID 58 items[newID] = item 59 60 return nil 61 } 62 63 func updateItem(id int64, item *models.Item) error { 64 if item == nil { 65 return errors.New(500, "item must be present") 66 } 67 68 itemsLock.Lock() 69 defer itemsLock.Unlock() 70 71 _, exists := items[id] 72 if !exists { 73 return errors.NotFound("not found: item %d", id) 74 } 75 76 item.ID = id 77 items[id] = item 78 return nil 79 } 80 81 func deleteItem(id int64) error { 82 itemsLock.Lock() 83 defer itemsLock.Unlock() 84 85 _, exists := items[id] 86 if !exists { 87 return errors.NotFound("not found: item %d", id) 88 } 89 90 delete(items, id) 91 return nil 92 } 93 94 func allItems(since int64, limit int32) (result []*models.Item) { 95 result = make([]*models.Item, 0) 96 for id, item := range items { 97 if len(result) >= int(limit) { 98 return 99 } 100 if since == 0 || id > since { 101 result = append(result, item) 102 } 103 } 104 return 105 } 106 107 func configureAPI(api *operations.TodoListAPI) http.Handler { 108 // configure the api here 109 api.ServeError = errors.ServeError 110 111 // Set your custom logger if needed. Default one is log.Printf 112 // Expected interface func(string, ...interface{}) 113 // 114 // Example: 115 // api.Logger = log.Printf 116 117 api.JSONConsumer = runtime.JSONConsumer() 118 119 api.JSONProducer = runtime.JSONProducer() 120 121 api.TodosAddOneHandler = todos.AddOneHandlerFunc( 122 func(params todos.AddOneParams) middleware.Responder { 123 if err := addItem(params.Body); err != nil { 124 return todos.NewAddOneDefault(500).WithPayload(&models.Error{Code: 500, Message: swag.String(err.Error())}) 125 } 126 return todos.NewAddOneCreated().WithPayload(params.Body) 127 }, 128 ) 129 api.TodosDestroyOneHandler = todos.DestroyOneHandlerFunc( 130 func(params todos.DestroyOneParams) middleware.Responder { 131 if err := deleteItem(params.ID); err != nil { 132 return todos.NewDestroyOneDefault(500).WithPayload(&models.Error{Code: 500, Message: swag.String(err.Error())}) 133 } 134 return todos.NewDestroyOneNoContent() 135 }, 136 ) 137 api.TodosFindTodosHandler = todos.FindTodosHandlerFunc( 138 func(params todos.FindTodosParams) middleware.Responder { 139 mergedParams := todos.NewFindTodosParams() 140 mergedParams.Since = swag.Int64(0) 141 if params.Since != nil { 142 mergedParams.Since = params.Since 143 } 144 if params.Limit != nil { 145 mergedParams.Limit = params.Limit 146 } 147 return todos.NewFindTodosOK().WithPayload(allItems(*mergedParams.Since, *mergedParams.Limit)) 148 }, 149 ) 150 api.TodosUpdateOneHandler = todos.UpdateOneHandlerFunc( 151 func(params todos.UpdateOneParams) middleware.Responder { 152 if err := updateItem(params.ID, params.Body); err != nil { 153 return todos.NewUpdateOneDefault(500).WithPayload(&models.Error{Code: 500, Message: swag.String(err.Error())}) 154 } 155 return todos.NewUpdateOneOK().WithPayload(params.Body) 156 }, 157 ) 158 159 api.ServerShutdown = func() {} 160 println(exampleFlags.Example1) 161 println(exampleFlags.Example2) 162 163 return setupGlobalMiddleware(api.Serve(setupMiddlewares)) 164 } 165 166 // The TLS configuration before HTTPS server starts. 167 func configureTLS(tlsConfig *tls.Config) { 168 // Make all necessary changes to the TLS configuration here. 169 } 170 171 // As soon as server is initialized but not run yet, this function will be called. 172 // If you need to modify a config, store server instance to stop it individually later, this is the place. 173 // This function can be called multiple times, depending on the number of serving schemes. 174 // scheme value will be set accordingly: "http", "https" or "unix". 175 func configureServer(s *http.Server, scheme, addr string) { 176 if exampleFlags.Example1 != "something" { 177 fmt.Print("example1 argument is not something") 178 } 179 } 180 181 // The middleware configuration is for the handler executors. These do not apply to the swagger.json document. 182 // The middleware executes after routing but before authentication, binding and validation. 183 func setupMiddlewares(handler http.Handler) http.Handler { 184 return handler 185 } 186 187 // The middleware configuration happens before anything, this middleware also applies to serving the swagger.json document. 188 // So this is a good place to plug in a panic handling middleware, logging and metrics. 189 func setupGlobalMiddleware(handler http.Handler) http.Handler { 190 return handler 191 }