1、简单实现
server
package main
import (
"flag"
"net/http"
)
func main() {
host := flag.String("host", "127.0.0.1", "listen host")
port := flag.String("port", "8080", "listen port")
http.HandleFunc("/helloworld", helloworld)
err := http.ListenAndServe(*host+":"+*port, nil)
if err != nil {
panic(err)
}
}
func helloworld(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("Hello World"))
}
client
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
response, _ := http.Get("http://localhost:8080/helloworld")
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
return
}
fmt.Println(string(body))
}
测试
运行服务器和客户端,打印Hello World
浏览器打开http://localhost:8080/helloworld,打印出Hello World
gitbash或者Linux终端,输入curl http://localhost:8080/helloworld
2、稍复杂的例子
package main
import (
"fmt"
"net/http"
"log"
)
type MyHandler map[string]string
var handler = MyHandler{"coco":"12"}
func (this MyHandler) list(w http.ResponseWriter, req *http.Request) {
for k,v := range this{
fmt.Fprintf(w, "%s : %s\n", k,v)
}
}
func (this MyHandler) GetPrice(w http.ResponseWriter, req *http.Request) {
price, ok := this["kaka"]
if !ok {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "no such item: kaka\n")
return
}
fmt.Fprintf(w, "kaka price:%s\n", price)
}
func (this MyHandler) SetPrice(w http.ResponseWriter, req *http.Request) {
price := "16"
handler["kaka"] = price
fmt.Fprintf(w, "set new item price to %s\n", price)
return
}
func main() {
mux := http.NewServeMux()
mux.Handle("/list", http.HandlerFunc(handler.list))
mux.Handle("/GetPrice", http.HandlerFunc(handler.GetPrice))
mux.Handle("/SetPrice", http.HandlerFunc(handler.SetPrice))
log.Fatal(http.ListenAndServe("localhost:8080", mux))
}
在gitbash或者Linux终端进行测试
curl http://localhost:8080/list
curl http://localhost:8080/SetPrice
curl http://localhost:8080/GetPrice