golang HTTP相关跨域问题、json传输的问题

首先是golang的跨域问题,这个之前在nginx配置中遇到过,关键字时all origin之类的东西,golang里面解决起来也很简单

w.Header().Set(“Access-Control-Allow-Origin”, “*”) //允许访问所有域 w.Header().Add(“Access-Control-Allow-Headers”, “Content-Type”) //header的类型

如下是修改golang返回数据未json的方法,只要设定了header之后直接

w.Header().Set(“content-type”, “application/json”) //返回数据格式是json

w.Write(js)

还有另外一种方法,参看链接


func main() {

`http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {</div> <div class="line number3 index2 alt2"> u := User{Id:“US123”, Balance:8}`</div> <div class="line number4 index3 alt1">`json.NewEncoder(w).Encode(u)</div> <div class="line number5 index4 alt2"> })`</div> <div class="line number6 index5 alt1">`log.Fatal(http.ListenAndServe(":8080", nil))</div> <div class="line number7 index6 alt2">}</div> </div> <div class="line number7 index6 alt2"></div> <div class="line number7 index6 alt2">---------------------------------------------------------------------</div> <div class="line number7 index6 alt2"> This is a pretty common task: encode JSON and send it to a server, decode JSON on the server, and vice versa. Amazingly, the existing resources on how to do this aren't very clear. So let's walk through each case, for the following simple User object: <div> <div id="highlighter_537062" class="syntaxhighlighter nogutter java"> <table border="0" cellspacing="0" cellpadding="0"> <tbody> <tr> <td class="code"> <div class="container"> <div class="line number1 index0 alt2">type User struct{</div> <div class="line number2 index1 alt1"> Id string`</div> <div class="line number3 index2 alt2">`Balance uint64</div> <div class="line number4 index3 alt1">}`






Sending JSON in the body of a POST/PUT request

Let’s start with the trickiest one: the body of a Go’s http.Request is an io.Reader, which doesn’t fit well if you have a struct - you need to write the struct first and then copy that to a reader.











func main() {

`u := User{Id: "US123", Balance: 8}</div> <div class="line number3 index2 alt2"> b :=new(bytes.Buffer)`</div> <div class="line number4 index3 alt1">`json.NewEncoder(b).Encode(u)</div> <div class="line number5 index4 alt2"> res, _ := http.Post(https://httpbin.org/post,“application/json; charset=utf-8”, b)`</div> <div class="line number6 index5 alt1">`io.Copy(os.Stdout, res.Body)</div> <div class="line number7 index6 alt2">}`



Decoding JSON on the server

Let’s say you’re expecting the client to send JSON data to the server. Easy, decode it with json.NewDecoder(r.Body).Decode(&amp;u). Here’s what that looks like with error handling:











func main() {

`http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {</div> <div class="line number3 index2 alt2"> var u User`</div> <div class="line number4 index3 alt1">`ifr.Body == nil {</div> <div class="line number5 index4 alt2"> http.Error(w,“Please send a request body”,400)`</div> <div class="line number6 index5 alt1">`return</div> <div class="line number7 index6 alt2"> }`</div> <div class="line number8 index7 alt1">`err := json.NewDecoder(r.Body).Decode(&u)</div> <div class="line number9 index8 alt2"> if` `err != nil {`</div> <div class="line number10 index9 alt1">`http.Error(w, err.Error(), 400)</div> <div class="line number11 index10 alt2"> return`</div> <div class="line number12 index11 alt1">`}</div> <div class="line number13 index12 alt2"> fmt.Println(u.Id)`</div> <div class="line number14 index13 alt1">`})</div> <div class="line number15 index14 alt2"> log.Fatal(http.ListenAndServe(“:8080”, nil))</div> <div class="line number16 index15 alt1">}`



Encoding JSON in a server response

Just the opposite of the above - call json.NewEncoder(w).Encode(&amp;u) to write JSON to the server.











func main() {

`http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {</div> <div class="line number3 index2 alt2"> u := User{Id:“US123”, Balance:8}`</div> <div class="line number4 index3 alt1">`json.NewEncoder(w).Encode(u)</div> <div class="line number5 index4 alt2"> })`</div> <div class="line number6 index5 alt1">`log.Fatal(http.ListenAndServe(":8080", nil))</div> <div class="line number7 index6 alt2">}`



Reading a JSON response from the server.

This time you’re going to read the response body in the client, after making the request.











func main() {

`u := User{Id: "US123", Balance: 8}</div> <div class="line number3 index2 alt2"> b :=new(bytes.Buffer)`</div> <div class="line number4 index3 alt1">`json.NewEncoder(b).Encode(u)</div> <div class="line number5 index4 alt2"> res, _ := http.Post(https://httpbin.org/post,“application/json; charset=utf-8”, b)`</div> <div class="line number6 index5 alt1">`var body struct {</div> <div class="line number7 index6 alt2"> // httpbin.org sends back key/value pairs, no map[string][]string`</div> <div class="line number8 index7 alt1">`Headers map[string]string json:`“headers”</div> <div class="line number9 index8 alt2">` ``Origin string `json:``"origin"

`}</div> <div class="line number11 index10 alt2"> json.NewDecoder(res.Body).Decode(&amp;body)`</div> <div class="line number12 index11 alt1">`fmt.Println(body)</div> <div class="line number13 index12 alt2">}`




That’s it! I hope it helps you a lot. Note that we only had to encode/decode the response to a byte array one time - in every other case we passed it directly to the reader/writer, which is one of the really nice things about Go, and interfaces - in most cases it’s really easy to pass around streams, instead of having to deal with the intermediate steps.

转载请注明来源链接 http://just4fun.im/2017/03/19/golang-http-e7-9b-b8-e5-85-b3-e8-b7-a8-e5-9f-9f-e9-97-ae-e9-a2-98-e3-80-81json-e4-bc-a0-e8-be-93-e7-9a-84-e9-97-ae-e9-a2-98/ 尊重知识,谢谢:)