github.com/circl-dev/go-swagger@v0.31.0/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  	runtime "github.com/circl-dev/runtime"
    13  	middleware "github.com/circl-dev/runtime/middleware"
    14  	errors "github.com/go-openapi/errors"
    15  	"github.com/go-openapi/swag"
    16  
    17  	"github.com/circl-dev/go-swagger/examples/tutorials/todo-list/server-complete/models"
    18  	"github.com/circl-dev/go-swagger/examples/tutorials/todo-list/server-complete/restapi/operations"
    19  	"github.com/circl-dev/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  		swag.CommandLineOptionsGroup{
    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(func(params todos.AddOneParams) middleware.Responder {
   122  		if err := addItem(params.Body); err != nil {
   123  			return todos.NewAddOneDefault(500).WithPayload(&models.Error{Code: 500, Message: swag.String(err.Error())})
   124  		}
   125  		return todos.NewAddOneCreated().WithPayload(params.Body)
   126  	})
   127  	api.TodosDestroyOneHandler = todos.DestroyOneHandlerFunc(func(params todos.DestroyOneParams) middleware.Responder {
   128  		if err := deleteItem(params.ID); err != nil {
   129  			return todos.NewDestroyOneDefault(500).WithPayload(&models.Error{Code: 500, Message: swag.String(err.Error())})
   130  		}
   131  		return todos.NewDestroyOneNoContent()
   132  	})
   133  	api.TodosFindTodosHandler = todos.FindTodosHandlerFunc(func(params todos.FindTodosParams) middleware.Responder {
   134  		mergedParams := todos.NewFindTodosParams()
   135  		mergedParams.Since = swag.Int64(0)
   136  		if params.Since != nil {
   137  			mergedParams.Since = params.Since
   138  		}
   139  		if params.Limit != nil {
   140  			mergedParams.Limit = params.Limit
   141  		}
   142  		return todos.NewFindTodosOK().WithPayload(allItems(*mergedParams.Since, *mergedParams.Limit))
   143  	})
   144  	api.TodosUpdateOneHandler = todos.UpdateOneHandlerFunc(func(params todos.UpdateOneParams) middleware.Responder {
   145  		if err := updateItem(params.ID, params.Body); err != nil {
   146  			return todos.NewUpdateOneDefault(500).WithPayload(&models.Error{Code: 500, Message: swag.String(err.Error())})
   147  		}
   148  		return todos.NewUpdateOneOK().WithPayload(params.Body)
   149  	})
   150  
   151  	api.ServerShutdown = func() {}
   152  	println(exampleFlags.Example1)
   153  	println(exampleFlags.Example2)
   154  
   155  	return setupGlobalMiddleware(api.Serve(setupMiddlewares))
   156  }
   157  
   158  // The TLS configuration before HTTPS server starts.
   159  func configureTLS(tlsConfig *tls.Config) {
   160  	// Make all necessary changes to the TLS configuration here.
   161  }
   162  
   163  // As soon as server is initialized but not run yet, this function will be called.
   164  // If you need to modify a config, store server instance to stop it individually later, this is the place.
   165  // This function can be called multiple times, depending on the number of serving schemes.
   166  // scheme value will be set accordingly: "http", "https" or "unix".
   167  func configureServer(s *http.Server, scheme, addr string) {
   168  	if exampleFlags.Example1 != "something" {
   169  		fmt.Print("example1 argument is not something")
   170  	}
   171  }
   172  
   173  // The middleware configuration is for the handler executors. These do not apply to the swagger.json document.
   174  // The middleware executes after routing but before authentication, binding and validation.
   175  func setupMiddlewares(handler http.Handler) http.Handler {
   176  	return handler
   177  }
   178  
   179  // The middleware configuration happens before anything, this middleware also applies to serving the swagger.json document.
   180  // So this is a good place to plug in a panic handling middleware, logging and metrics.
   181  func setupGlobalMiddleware(handler http.Handler) http.Handler {
   182  	return handler
   183  }