github.com/circl-dev/go-swagger@v0.31.0/examples/tutorials/todo-list/dynamic-setup/main.go (about)

     1  package main
     2  
     3  import (
     4  	"log"
     5  	"net/http"
     6  	"os"
     7  
     8  	"github.com/circl-dev/loads"
     9  	"github.com/circl-dev/loads/fmts"
    10  	"github.com/circl-dev/runtime"
    11  	"github.com/circl-dev/runtime/middleware"
    12  	"github.com/circl-dev/runtime/middleware/untyped"
    13  )
    14  
    15  func init() {
    16  	loads.AddLoader(fmts.YAMLMatcher, fmts.YAMLDoc)
    17  }
    18  
    19  func main() {
    20  	if len(os.Args) == 1 {
    21  		log.Fatalln("this command requires the swagger spec as argument")
    22  	}
    23  	log.Printf("loading %q as contract for the server", os.Args[1])
    24  
    25  	specDoc, err := loads.Spec(os.Args[1])
    26  	if err != nil {
    27  		log.Fatalln(err)
    28  	}
    29  
    30  	// our spec doesn't have application/json in the consumes or produces
    31  	// so we need to clear those settings out
    32  	api := untyped.NewAPI(specDoc).WithoutJSONDefaults()
    33  
    34  	// register serializers
    35  	mediaType := "application/io.goswagger.examples.todo-list.v1+json"
    36  	api.DefaultConsumes = mediaType
    37  	api.DefaultProduces = mediaType
    38  	api.RegisterConsumer(mediaType, runtime.JSONConsumer())
    39  	api.RegisterProducer(mediaType, runtime.JSONProducer())
    40  
    41  	// register the operation handlers
    42  	api.RegisterOperation("GET", "/", notImplemented)
    43  	api.RegisterOperation("POST", "/", notImplemented)
    44  	api.RegisterOperation("PUT", "/{id}", notImplemented)
    45  	api.RegisterOperation("DELETE", "/{id}", notImplemented)
    46  
    47  	// validate the API descriptor, to ensure we don't have any unhandled operations
    48  	if err := api.Validate(); err != nil {
    49  		log.Fatalln(err)
    50  	}
    51  
    52  	// construct the application context for this server
    53  	// use the loaded spec document and the api descriptor with the default router
    54  	app := middleware.NewContext(specDoc, api, nil)
    55  
    56  	log.Println("serving", specDoc.Spec().Info.Title, "at http://localhost:8000")
    57  	// serve the api
    58  	if err := http.ListenAndServe(":8000", app.APIHandler(nil)); err != nil {
    59  		log.Fatalln(err)
    60  	}
    61  }
    62  
    63  var notImplemented = runtime.OperationHandlerFunc(func(params interface{}) (interface{}, error) {
    64  	return middleware.NotImplemented("not implemented"), nil
    65  })