Skip to content

Commit c3754ea

Browse files
authored
Merge pull request #87 from fredbi/fix-1846
Fix go-swagger/go-swagger#1816
2 parents 5bae59e + c166dd3 commit c3754ea

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

ref.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
package spec
1616

1717
import (
18+
"bytes"
19+
"encoding/gob"
1820
"encoding/json"
1921
"net/http"
2022
"os"
@@ -148,6 +150,28 @@ func (r *Ref) UnmarshalJSON(d []byte) error {
148150
return r.fromMap(v)
149151
}
150152

153+
// GobEncode provides a safe gob encoder for Ref
154+
func (r Ref) GobEncode() ([]byte, error) {
155+
var b bytes.Buffer
156+
raw, err := r.MarshalJSON()
157+
if err != nil {
158+
return nil, err
159+
}
160+
err = gob.NewEncoder(&b).Encode(raw)
161+
return b.Bytes(), err
162+
}
163+
164+
// GobDecode provides a safe gob decoder for Ref
165+
func (r *Ref) GobDecode(b []byte) error {
166+
var raw []byte
167+
buf := bytes.NewBuffer(b)
168+
err := gob.NewDecoder(buf).Decode(&raw)
169+
if err != nil {
170+
return err
171+
}
172+
return json.Unmarshal(raw, r)
173+
}
174+
151175
func (r *Ref) fromMap(v map[string]interface{}) error {
152176
if v == nil {
153177
return nil

ref_test.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Copyright 2015 go-swagger maintainers
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package spec
16+
17+
import (
18+
"bytes"
19+
"encoding/gob"
20+
"encoding/json"
21+
"testing"
22+
23+
"github.com/stretchr/testify/assert"
24+
)
25+
26+
// pin pointing go-swagger/go-swagger#1816 issue with cloning ref's
27+
func TestCloneRef(t *testing.T) {
28+
var b bytes.Buffer
29+
src := MustCreateRef("#/definitions/test")
30+
err := gob.NewEncoder(&b).Encode(&src)
31+
if !assert.NoError(t, err) {
32+
t.FailNow()
33+
}
34+
35+
var dst Ref
36+
err = gob.NewDecoder(&b).Decode(&dst)
37+
if !assert.NoError(t, err) {
38+
t.FailNow()
39+
}
40+
41+
jazon, err := json.Marshal(dst)
42+
if !assert.NoError(t, err) {
43+
t.FailNow()
44+
}
45+
46+
assert.Equal(t, `{"$ref":"#/definitions/test"}`, string(jazon))
47+
}

0 commit comments

Comments
 (0)