initial import

This commit is contained in:
SourceFellows
2020-08-21 06:26:40 +02:00
commit e223458dd4
423 changed files with 9871 additions and 0 deletions

View File

@ -0,0 +1,3 @@
module golang.source-fellows.com/samples/http-server-test
go 1.14

View File

@ -0,0 +1,29 @@
package main
import (
"net/http"
)
var jsonDoc1 = []byte("{\"Name\":\"")
var jsonDoc2 = []byte("\"}")
func myHandler(writer http.ResponseWriter, req *http.Request) {
path := req.URL.Path
if len(path) < 6 || path[:6] != "/json/" {
writer.WriteHeader(http.StatusNotImplemented)
return
}
writer.Header().Add("Content-Type", "application/json")
bites := make([]byte, 20)
bites = append(bites, jsonDoc1...)
bites = append(bites, path[6:]...)
bites = append(bites, jsonDoc2...)
writer.Write(bites)
}
func main() {
http.HandleFunc("/", myHandler)
http.ListenAndServe(":8080", nil)
}

View File

@ -0,0 +1,40 @@
package main
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func Test_myHandler(t *testing.T) {
type args struct {
url string
expectedName string
status int
}
tests := []struct {
name string
args args
}{
{"t1", args{"/json/test", "test", http.StatusOK}},
{"t2", args{"/x/y", "", http.StatusNotImplemented}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
url := tt.args.url
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
t.Errorf("could't create request: %v", tt.args.url)
}
recorder := httptest.NewRecorder()
myHandler(recorder, req)
if recorder.Result().StatusCode != tt.args.status {
t.Errorf("Wrong status code %v, expected %v", recorder.Result().StatusCode, tt.args.status)
}
if !strings.Contains(recorder.Body.String(), tt.args.expectedName) {
t.Errorf("The response does't contain '%v': '%v'", tt.args.expectedName, recorder.Body.String())
}
})
}
}