Last active
December 19, 2018 09:31
-
-
Save vyskocilm/3007ce0754d86b7e7b0754383b46b2a1 to your computer and use it in GitHub Desktop.
Testing cors.Cors and golang net/http
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// simple net/http + cors.Cors integration | |
// vyskocilm.github.io/blog | |
// | |
package main | |
import ( | |
"fmt" | |
"log" | |
"net/http" | |
"github.com/rs/cors" | |
) | |
type Srv struct { | |
mux *http.ServeMux | |
cors *cors.Cors | |
} | |
func NewSrv() *Srv { | |
s := &Srv{} | |
s.mux = http.NewServeMux() | |
s.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, "<html>Hello world</html>\n") | |
}) | |
s.cors = cors.Default() | |
return s | |
} | |
// return top level http.Handler | |
func (s *Srv) Handler() http.Handler { | |
return s.cors.Handler(s.mux) | |
} | |
func (s *Srv) ListenAndServe(port string) error { | |
return http.ListenAndServe(port, s.Handler()) | |
} | |
func main() { | |
s := NewSrv() | |
log.Fatal( | |
s.ListenAndServe(":8000")) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"net/http" | |
"net/http/httptest" | |
"testing" | |
"github.com/stretchr/testify/assert" | |
"github.com/stretchr/testify/require" | |
) | |
var ( | |
s *Srv | |
) | |
func init() { | |
s = NewSrv() | |
} | |
func Test1(t *testing.T) { | |
require := require.New(t) | |
assert := assert.New(t) | |
r, e := http.NewRequest("POST", "/", nil) | |
r.Header.Set("Origin", "http://example.com") | |
require.NoError(e) | |
w := httptest.NewRecorder() | |
handler := s.Handler() | |
handler.ServeHTTP(w, r) | |
assert.Contains(w.Header(), "Vary") | |
assert.Equal("Origin", w.Header().Get("Vary")) | |
assert.Contains(w.Header(), "Content-Type") | |
assert.Contains(w.Header(), "Access-Control-Allow-Origin") | |
assert.Equal("*", w.Header().Get("Access-Control-Allow-Origin")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment