Skip to content

Instantly share code, notes, and snippets.

@axiaoxin
Last active December 27, 2018 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save axiaoxin/aa8014738c6a02ce4e66eb01168d24fe to your computer and use it in GitHub Desktop.
Save axiaoxin/aa8014738c6a02ce4e66eb01168d24fe to your computer and use it in GitHub Desktop.
mockHTTPServer.go
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: "254606826@qq.com",
}
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