golang 实现http mock server

源码来自 https://github.com/deis/mock-http-server

 

主要作用是开启一个本地的监听8080端口的http服务器,能够打印客户端的请求,方便进行调试。

package main

import (
	"fmt"
	"log"
	"net/http"
)

// Log the HTTP request
func logHandler(w http.ResponseWriter, r *http.Request) {
	log.Printf("%s %s %s", r.RemoteAddr, r.Method, r.URL)
}

// mockHandler responds with "ok" as the response body
func mockHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "ok\n")
}

// rootHandler used to process all inbound HTTP requests
func rootHandler(w http.ResponseWriter, r *http.Request) {
	logHandler(w, r)
	mockHandler(w, r)
}

// Start an HTTP server which dispatches to the rootHandler
func main() {
	http.HandleFunc("/", rootHandler)
	port := "8080"
	log.Printf("server is listening on %v\n", port)
	err := http.ListenAndServe(":"+port, nil)
	if err != nil {
		panic(err)
	}
}

如果需要打印header,请参考:https://www.cnblogs.com/5bug/p/8494953.html

func helloFunc(w http.ResponseWriter, r *http.Request)  {
   fmt.Println("打印Header参数列表:")
   if len(r.Header) > 0 {
      for k,v := range r.Header {
         fmt.Printf("%s=%s\n", k, v[0])
      }
   }
   fmt.Println("打印Form参数列表:")
   r.ParseForm()
   if len(r.Form) > 0 {
      for k,v := range r.Form {
         fmt.Printf("%s=%s\n", k, v[0])
      }
   }

 

上完整版程序,支持json改变监听端口的。

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strconv"
)

// Log the HTTP request
func logHandler(w http.ResponseWriter, r *http.Request) {
	log.Printf("%s %s %s", r.RemoteAddr, r.Method, r.URL)
}

// mockHandler responds with "ok" as the response body
func mockHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "ok\n")
}

func headerFunc(w http.ResponseWriter, r *http.Request) {
	if len(r.Header) > 0 {
		for k, v := range r.Header {
			fmt.Printf("%s=%s\n", k, v[0])
		}
	}

	r.ParseForm()
	if len(r.Form) > 0 {
		for k, v := range r.Form {
			fmt.Printf("%s=%s\n", k, v[0])
		}
	}
}

// rootHandler used to process all inbound HTTP requests
func rootHandler(w http.ResponseWriter, r *http.Request) {
	logHandler(w, r)
	headerFunc(w, r)
	mockHandler(w, r)
}

type API struct {
	Port int `json:"port"`
}

var api API

// Start an HTTP server which dispatches to the rootHandler
func main() {
	raw, err := ioutil.ReadFile("./api.json")
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}

	json.Unmarshal(raw, &api)
	if err != nil {
		log.Fatal(" ", err)
	}

	port := strconv.Itoa(api.Port) //"8080"

	http.HandleFunc("/", rootHandler)

	log.Printf("server is listening on %v\n", port)
	err = http.ListenAndServe(":"+port, nil)
	if err != nil {
		panic(err)
	}
}

api.json内容 

{
  "port": 8081 
}

 

你可能感兴趣的:(golang)