golang构建htpp服务

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值