Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/ma91n/go-swagger-httptest

POC: go-swagger server exmaple impl that using httptest
https://github.com/ma91n/go-swagger-httptest

Last synced: 6 days ago
JSON representation

POC: go-swagger server exmaple impl that using httptest

Awesome Lists containing this project

README

        

# go-swagger-httptest
POC: go-swagger server example impl that using httptest

## Abstract

Using httptest with server code generated by go-swagger does not support officially.

https://github.com/go-swagger/go-swagger/issues/719

So it might be Dirty Hack, but I tried using httptest.

see `hello_test.go`

## How to use go-swagger serverside with httptest

Add exposed function that return http.Handler in [configure_${your-project}.go](https://github.com/laqiiz/go-swagger-httptest/blob/master/gen/restapi/configure_hello.go#L25)

```go:restpi.configure_hello.go
func ConfigureAPI(api *hello.HelloAPI) http.Handler {
return configureAPI(api)
}
```

You create handler in your [test code](https://github.com/laqiiz/go-swagger-httptest/blob/master/hello_test.go#L14).

```go hello_test.go
func HelloHandler() (http.Handler, error) {
swaggerSpec, err := loads.Embedded(restapi.SwaggerJSON, restapi.FlatSwaggerJSON)
if err != nil {
return nil, err
}

api := hello.NewHelloAPI(swaggerSpec)
h := restapi.ConfigureAPI(api)

return h, nil
}

func TestHello(t *testing.T) {

h, err := HelloHandler()
if err != nil {
t.Fatal("api handler", err)
}

ts := httptest.NewServer(h)
defer ts.Close()

// httptest request
resp, err := http.Get(ts.URL + "/v1/hello")
}
```

## Memo

generate `gen` directory.

```sh
go get -u github.com/go-swagger/[email protected]
swagger generate server -a hello -A hello --strict-additional-properties -t gen
```