golang实现get,post请求,传送json数据

Posted tower888

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang实现get,post请求,传送json数据相关的知识,希望对你有一定的参考价值。

package main

import (
	"encoding/json"
	"fmt"
	"github.com/gorilla/mux"
	"log"
	"net/http"
	"time"
)

func main() 
	router := mux.NewRouter().StrictSlash(true)
	router.HandleFunc("/", Index)
	router.HandleFunc("/todos", TodoIndex)
	//curl  -H "Content-Type:application/json" -X GET  -i  'http://127.0.0.1:8080/todos/123/zgx'
	router.HandleFunc("/todos/todoId/name", TodoShow)
	
	//curl  -H "Content-Type:application/json" -X POST -d '"name":"zgx","age":30'  -i  'http://127.0.0.1:8080/handlePostJson' 
	router.HandleFunc("/handlePostJson", handlePostJson)

	log.Fatal(http.ListenAndServe(":8080", router))


func handlePostJson(w http.ResponseWriter, r *http.Request) 
	decoder:=json.NewDecoder(r.Body)
	var params map[string]interface
	decoder.Decode(&params)
	fmt.Println("POST json req: ",params)
	fmt.Fprintln(w,`"code":0,"msg":"succ"`)


func Index(w http.ResponseWriter, r *http.Request) 
	fmt.Fprintln(w, "Welcome!")


func TodoIndex(w http.ResponseWriter, r *http.Request) 
	//params:= r.URL.Query()
	//username:= params.Get("username")
	//fmt.Println("request: ",username)

	servicetype := r.PostFormValue("servicetype")
	fmt.Println("request: ", servicetype)

	fmt.Fprintln(w, "Todo Index!")
	type Todos []Todo
	todos := Todos
		TodoName: "Write presentation",
		TodoName: "Host meetup",
	
	if err := json.NewEncoder(w).Encode(todos); err != nil 
		panic(err)
	


type Todo struct 
	Name      string    `json:"name"`
	Completed bool      `json:"completed"`
	Due       time.Time `json:"due"`


func TodoShow(w http.ResponseWriter, r *http.Request) 
	vars := mux.Vars(r)
	todoId := vars["todoId"]
	name := vars["name"]
	fmt.Println("request: ", vars)
	fmt.Fprintln(w, "response: Id:", todoId, "name:", name)

 

以上是关于golang实现get,post请求,传送json数据的主要内容,如果未能解决你的问题,请参考以下文章

golang实现get和post请求的服务端和客户端

golang原生api实现get和post

golang http库的使用 并发 get post请求处理

httpclient能通过get类型请求发送json数据吗?

getmethod如何发送json数据

golang使用http client发起get和post请求示例