package main
import (
"io"
"net/http"
"encoding/json"
)
type Repay struct {
Code uint64 `json:"code"`
Message string `json:"message"`
}
var msg []byte
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/hi", sayHi)
mux.Handle("/", &MyHandler{})
if err := http.ListenAndServe("127.0.0.1:8080", mux); err != nil {
panic(err)
}
}
func sayHi(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "hi, this is cutom mux")
}
type MyHandler struct {
}
func (mh *MyHandler)ServeHTTP(w http.ResponseWriter, r *http.Request) {
Repays := &Repay{1,"succ"}
msg, _ = json.Marshal(Repays)
w.Header().Set("content-type","text/json")
w.Write(msg)
}
main_test.go
package main
import (
"testing"
"net/http"
"net/http/httptest"
"fmt"
)
func TestMain(m *testing.M) {
m.Run()
}
func TestHello(t *testing.T){
req, err := http.NewRequest("GET", "/hi",nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := http.Handler(&MyHandler{})
handler.ServeHTTP(rr, req)
fmt.Println(rr.Body.String())
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
}
|