redone the test and go codes
This commit is contained in:
17
main.go
17
main.go
@@ -1,20 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Server struct{}
|
||||
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"message": "Hello world"}`))
|
||||
}
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
s := &Server{}
|
||||
http.Handle("/", s)
|
||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||
fmt.Println("Hello World")
|
||||
}
|
||||
|
||||
34
main_test.go
34
main_test.go
@@ -1,20 +1,30 @@
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type Server struct{}
|
||||
func TestHelloWorld(t *testing.T) {
|
||||
rescueStdout := os.Stdout
|
||||
r, w, _ := os.Pipe()
|
||||
os.Stdout = w
|
||||
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"message": "hello world"}`))
|
||||
}
|
||||
main()
|
||||
|
||||
func main() {
|
||||
s := &Server{}
|
||||
http.Handle("/", s)
|
||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||
w.Close()
|
||||
out, _ := ioutil.ReadAll(r)
|
||||
os.Stdout = rescueStdout
|
||||
|
||||
fmt.Println(string(out))
|
||||
|
||||
var outputString string = string(out)
|
||||
|
||||
if strings.TrimSpace(outputString) != "Hello World" {
|
||||
t.Errorf("Expected %s, got %s", "Hello World", out)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user