Last active
December 27, 2018 09:25
-
-
Save axiaoxin/aa8014738c6a02ce4e66eb01168d24fe to your computer and use it in GitHub Desktop.
mockHTTPServer.go
This file contains 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 ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"net/http/httptest" | |
) | |
func MockHTTPServer(f http.HandlerFunc) *httptest.Server { | |
return httptest.NewServer(http.HandlerFunc(f)) | |
} | |
func mockHandler(w http.ResponseWriter, r *http.Request) { | |
u := struct { | |
Name string | |
Email string | |
}{ | |
Name: "axiaoxin", | |
Email: "[email protected]", | |
} | |
w.WriteHeader(200) | |
w.Header().Set("Content-Type", "application/json") | |
json.NewEncoder(w).Encode(&u) | |
} | |
func main() { | |
s := MockHTTPServer(mockHandler) | |
defer s.Close() | |
resp, err := http.Get(s.URL) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer resp.Body.Close() | |
body, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("url:%s response:%s", s.URL, string(body)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment