golang编写http server

golang 构建HTTP服务_冷月醉雪的博客-CSDN博客_golang http

Go net/http获取body中json格式数据 - impluse - 博客园

package main

import (
	"log"
	"net/http"

	"github.com/gorilla/mux"
)

func get(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(`{"message": "get called"}`))
}

func test2(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(`{"message": "test2 called"}`))
}

func test(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(`{"message": "post called"}`))
}

func put(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusAccepted)
	w.Write([]byte(`{"message": "put called"}`))
}

func delete(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(`{"message": "delete called"}`))
}

func notFound(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusNotFound)
	w.Write([]byte(`{"message": "not found"}`))
}

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", get).Methods(http.MethodGet)
	r.HandleFunc("/test2/", test2).Methods(http.MethodPost)
	r.HandleFunc("/test/", test).Methods(http.MethodPost)
	r.HandleFunc("/", put).Methods(http.MethodPut)
	r.HandleFunc("/", delete).Methods(http.MethodDelete)
	r.HandleFunc("/", notFound)
	log.Fatal(http.ListenAndServe(":8080", r))
}

package main
 
import (
    "fmt"
    "io/ioutil"
    //    "log"
    "net/http"
    //    "strings"
    "bytes"
    "encoding/json"
)
 
type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}
 
func main() {
    resp, _ := http.Get("http://192.168.111.142:8080/?a=123456&b=aaa&b=bbb")
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
 
    var user User
    user.Name = "aaa"
    user.Age = 99
    if bs, err := json.Marshal(user); err == nil {
        //        fmt.Println(string(bs))
        req := bytes.NewBuffer([]byte(bs))
        tmp := `{"name":"junneyang", "age": 88}`
        req = bytes.NewBuffer([]byte(tmp))
 
        body_type := "application/json;charset=utf-8"
        resp, _ = http.Post("http://192.168.111.142:8080/test/", body_type, req)
        body, _ = ioutil.ReadAll(resp.Body)
        fmt.Println(string(body))
    } else {
        fmt.Println(err)
    }
 
    client := &http.Client{}
    request, _ := http.NewRequest("GET", "http://192.168.111.142:8080/?a=123456&b=aaa&b=bbb", nil)
    request.Header.Set("Connection", "keep-alive")
    response, _ := client.Do(request)
    if response.StatusCode == 200 {
        body, _ := ioutil.ReadAll(response.Body)
        fmt.Println(string(body))
    }
 
    req := `{"name":"junneyang", "age": 88}`
    req_new := bytes.NewBuffer([]byte(req))
    request, _ = http.NewRequest("POST", "http://192.168.111.142:8080/test2/", req_new)
    request.Header.Set("Content-type", "application/json")
    response, _ = client.Do(request)
    if response.StatusCode == 200 {
        body, _ := ioutil.ReadAll(response.Body)
        fmt.Println(string(body))
    }
}

go语言实现httpserver

go语言实现httpserver_jason_新浪博客

g】golang HTTP GET/POST JSON的服务端、客户端示例,包含序列化、反序列化

【GoLang】golang HTTP GET/POST JSON的服务端、客户端示例,包含序列化、反序列化 - junneyang - 博客园

package main

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

type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func index(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    fmt.Println("Form: ", r.Form)
    fmt.Println("Path: ", r.URL.Path)
    fmt.Println(r.Form["a"])
    fmt.Println(r.Form["b"])
    for k, v := range r.Form {
        fmt.Println(k, "=>", v, strings.Join(v, "-"))
    }
    fmt.Fprint(w, "It works !")
}

func test(w http.ResponseWriter, r *http.Request) {
    body, _ := ioutil.ReadAll(r.Body)
    //    r.Body.Close()
    body_str := string(body)
    fmt.Println(body_str)
    //    fmt.Fprint(w, body_str)
    var user User
    //    user.Name = "aaa"
    //    user.Age = 99
    //    if bs, err := json.Marshal(user); err == nil {
    //        fmt.Println(string(bs))
    //    } else {
    //        fmt.Println(err)
    //    }

    if err := json.Unmarshal(body, &user); err == nil {
        fmt.Println(user)
        user.Age += 100
        fmt.Println(user)
        ret, _ := json.Marshal(user)
        fmt.Fprint(w, string(ret))
    } else {
        fmt.Println(err)
    }
}

func main() {
    http.HandleFunc("/", index)
    http.HandleFunc("/test/", test)

    if err := http.ListenAndServe("0.0.0.0:8080", nil); err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

客户端代码

package main

import (
    "fmt"
    "io/ioutil"
    //    "log"
    "net/http"
    //    "strings"
    "bytes"
    "encoding/json"
)

type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    resp, _ := http.Get("http://10.67.2.252:8080/?a=123456&b=aaa&b=bbb")
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))

    var user User
    user.Name = "aaa"
    user.Age = 99
    if bs, err := json.Marshal(user); err == nil {
        //        fmt.Println(string(bs))
        req := bytes.NewBuffer([]byte(bs))
        tmp := `{"name":"junneyang", "age": 88}`
        req = bytes.NewBuffer([]byte(tmp))

        body_type := "application/json;charset=utf-8"
        resp, _ = http.Post("http://10.67.2.252:8080/test/", body_type, req)
        body, _ = ioutil.ReadAll(resp.Body)
        fmt.Println(string(body))
    } else {
        fmt.Println(err)
    }

    client := &http.Client{}
    request, _ := http.NewRequest("GET", "http://10.67.2.252:8080/?a=123456&b=aaa&b=bbb", nil)
    request.Header.Set("Connection", "keep-alive")
    response, _ := client.Do(request)
    if response.StatusCode == 200 {
        body, _ := ioutil.ReadAll(response.Body)
        fmt.Println(string(body))
    }

    req := `{"name":"junneyang", "age": 88}`
    req_new := bytes.NewBuffer([]byte(req))
    request, _ = http.NewRequest("POST", "http://10.67.2.252:8080/test/", req_new)
    request.Header.Set("Content-type", "application/json")
    response, _ = client.Do(request)
    if response.StatusCode == 200 {
        body, _ := ioutil.ReadAll(response.Body)
        fmt.Println(string(body))
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值