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